﻿using GYCTOAManagementSystem.Models.Enum;
using GYCTOAManagementSystemNewApi.Model;
using GYCTOAManagementSystemNewApi.Model.Enum;
using GYCTOAManagementSystemNewApi.Model.Tool;
using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using GYCTOAManagementSystemNewApi.Tool;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using GYCTOAManagementSystemNewApi.Controllers;
using DingTalk.Api;
using DingTalk.Api.Request;
using DingTalk.Api.Response;
using System.IO;
using System.Data;
using System.Text.RegularExpressions;
using System.Text; 
using Jiguang.JPush;
using Jiguang.JPush.Model;
using GYCTOAManagementSystemNewApi.Controllers.PublicController;
using MySqlConnector;
using static System.Net.Mime.MediaTypeNames;
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using System.Net;
using PdfSharp.UniversalAccessibility.Drawing;
using PdfSharp;
using SharpCompress.Common;
using Microsoft.AspNetCore.Mvc;
using OfficeOpenXml;
using System.Reflection.Metadata;
using GYCTOAManagementSystemNewApi.Model.Entity;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using GYCTOAManagementSystemNewApi.Model.Response;
using GYCTOAManagementSystemNewApi.Model.Request;
using GYCTOAManagementSystemNewApi.Model.DTO;

namespace GYCTOAManagementSystemNewApi.Public
{
    /// <summary>
    /// 通用公共类
    /// </summary>
    public class PublicTool
    {
        static DBContext db;
        private static string strcon = string.Empty;
        public static string APP_KEY = string.Empty;
        public static string MASTER_SECRET = string.Empty;
        private static readonly object Form_lock = new object();
        public PublicTool(DBContext bContext)
        {
            strcon = ConfigurationHelper.GetConfigValueByKey("ConnectionStrings:DefaultConnection");
            APP_KEY = ConfigurationHelper.GetConfigValueByKey("JiguangSetting:APP_KEY");
            MASTER_SECRET = ConfigurationHelper.GetConfigValueByKey("JiguangSetting:MASTER_SECRET");
            db = bContext;
        }
        public PublicTool()
        {
        }
        public static long tpl_Purchase_id = 516927;//采购与物资的审批短信模板码
        public static long tpl_PurchaseReceipt_id = 518648;//采购与物资的审批短信回执模板码
        public static long tpl_ProjectReport_id = 568991;//项目报表的审批短信模板码
        public static long tpl_AuditRefuse_id = 657572;//审批拒绝模板码

        public static string OAFile = "OAFile";//图片路径表头
        static Access access = Access.GetAccess();//钉钉接口认证内容

        public static string locahosturl = "http://192.168.0.142:8090/";
        public static string onlineurl = "http://101.204.227.175:83/";

        #region OA权限码
        public static readonly string Admin = "Admin";
        #endregion

        #region 菜单编码
        /// <summary>
        /// 支付管理菜单
        /// </summary>
        public static readonly string ModuleEnum_Loan = "0" + (int)ModuleEnum.Loan;
        /// <summary>
        /// 报销管理菜单
        /// </summary>
        public static readonly string ModuleEnum_Reim = "0" + (int)ModuleEnum.Reim;
        /// <summary>
        /// 开票管理菜单
        /// </summary>
        public static readonly string ModuleEnum_Invoice = "0" + (int)ModuleEnum.Invoice;
        /// <summary>
        /// 申购管理菜单
        /// </summary>
        public static readonly string ModuleEnum_ApplyPurchase = "0" + (int)ModuleEnum.ApplyPurchase;
        /// <summary>
        /// 采购管理菜单
        /// </summary>
        public static readonly string ModuleEnum_Purchase = "0" + (int)ModuleEnum.Purchase;
        /// <summary>
        /// 入库单菜单
        /// </summary>
        public static readonly string ModuleEnum_Inbound = "0" + (int)ModuleEnum.InboundOrder;
        /// <summary>
        /// 出库单菜单
        /// </summary>
        public static readonly string ModuleEnum_Outbound = "0" + (int)ModuleEnum.OutboundOrder;
        /// <summary>
        /// 归还单菜单
        /// </summary>
        public static readonly string ModuleEnum_Return = "0" + (int)ModuleEnum.ReturnboundOrder;
        /// <summary>
        /// 公章使用单菜单
        /// </summary>
        public static readonly string ModuleEnum_Offical = "" + (int)ModuleEnum.OfficialSealOrder;
        #endregion

        #region 补足位数
        public static string ComplementDigit(int length, string data)
        {
            string result = string.Empty;
            for (int i = 0; i < length - data.Length; i++)
            {
                result += "0";
            }
            return result + data;
        }
        #endregion

        #region 添加最后修改时间,人员

        public static T GetOpDataOpId<T>(T t, string author) where T : Operate
        {
            var logid = TokenManage.GetTokenValues(author)[0].Value;
            t.OperatDate = DateTime.Now;
            t.OperatId = Convert.ToInt32(logid);
            return t;
        }

        #endregion


        /// <summary>
        /// 根据用户ID，获取用户所有信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public static Users GetUsers(int Id)
        {
            Users user = db.Users.Where(l => l.Id == Id).FirstOrDefault();
            return user;
        }
        /// <summary>
        /// 获取所有在职员工
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public static List<Users> GetAllOnTheJobUsers()
        {
            List<Users> users = db.Users.Where(x => !x.Delete && x.InternshipState != (int)InternshipStateEnum.Quit).ToList();
            return users;
        }

        /// <summary>
        /// 设置最大的采购编号
        /// </summary>
        /// <returns></returns>
        public string SetMaxPurchaseNumber(string maxNumber)
        {
            string result = "";
            var date = DateTime.Now.ToString("yyyyMMdd");
            if (maxNumber == null)
            {
                result = date + "001";
            }
            else
            {
                var maxDate = maxNumber.Substring(0, 8);
                var number = maxNumber.Substring(8, 3);
                if (maxDate == date)
                {
                    var newNumber = (Convert.ToInt32(number) + 1).ToString();
                    while (newNumber.Length < 3)
                    {
                        newNumber = "0" + newNumber;
                    }
                    result = date + newNumber;
                }
                else
                {
                    result = date + "001";
                }
            }
            return result;
        }
        /// <summary>
        /// 获取枚举的描述
        /// </summary>
        /// <param name="en">枚举</param>
        /// <returns>返回枚举的描述</returns>
        public static string GetDescription(Enum en)
        {
            Type type = en.GetType();   //获取类型
            MemberInfo[] memberInfos = type.GetMember(en.ToString());   //获取成员
            if (memberInfos != null && memberInfos.Length > 0)
            {
                DescriptionAttribute[] attrs = memberInfos[0].GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];   //获取描述特性
                if (attrs != null && attrs.Length > 0)
                {
                    return attrs[0].Description;    //返回当前描述
                }
            }
            return en.ToString();
        }


        /// <summary>
        /// 根据用户id和模块编号，查找相应的审批规则
        /// </summary>
        /// <param name="ModuleNumber">模块编号</param>
        /// <param name="SponsorUserid">数据对应用户id</param>
        /// <returns></returns>
        public static AuditRule GetAuditRule(string ModuleNumber, int SponsorUserid, DBContext db)
        {
            AuditRule auditrule = null;
            //lock (Form_lock)
            //{
            var user = db.Users.Where(x => x.Id == SponsorUserid).FirstOrDefault();
            if (user == null) return auditrule;
            List<AuditRule> auditRules = db.AuditRule.Where(x => !x.Delete && x.ModuleNumber == ModuleNumber).ToList();
            foreach (var a in auditRules)
            {
                if (a.SponsorUser != null && a.SponsorUser.Split(',').Contains(SponsorUserid.ToString()))
                {
                    auditrule = a;
                    break;
                }
            }
            //if (auditrule == null)
            //{
            //    foreach (var a in auditRules)
            //    {
            //        if (a.SponsorDepart != null && a.SponsorDepart.Split(',').Contains(user.DepartmentId.ToString()))
            //        {
            //            auditrule = a;
            //            break;
            //        }
            //    }
            //}
            //}
            return auditrule;
        }
        /// <summary>
        /// 筛选未审核的单据,20220314增加限定条件，排除已审核完毕的单据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="datas"></param>
        /// <param name="l"></param>
        /// <param name="auditRule"></param>
        /// <param name="userId"></param>
        public static void NoChecked<T>(List<T> datas, T l, AuditRule auditRule, int userId) where T : PublicAudit
        {
            if (auditRule != null && !l.IsRefuse && !l.IsAuditEnd)
            {
                if (userId == auditRule.AuditUserId1 && l.State == (int)AuditStateEnum.WaitApprove)
                {
                    datas.Add(l);
                }
                else if (userId == auditRule.AuditUserId2 && l.State == (int)AuditStateEnum.One)
                {
                    datas.Add(l);
                }
                else if (userId == auditRule.AuditUserId3 && l.State == (int)AuditStateEnum.Two)
                {
                    datas.Add(l);
                }
                else if (userId == auditRule.AuditUserId4 && l.State == (int)AuditStateEnum.Three)
                {
                    datas.Add(l);
                }
                else if (userId == auditRule.AuditUserId5 && l.State == (int)AuditStateEnum.Four)
                {
                    datas.Add(l);
                }
                else if (userId == auditRule.AuditUserId6 && l.State == (int)AuditStateEnum.Five)
                {
                    datas.Add(l);
                }
            }
        }

        #region 前台页面弹出框
        public static string WebPopup(string mes = "该记录不存在")
        {
            string RecordNotExist = @"<script>document.write('<link href=../Content/XAdmin/lib/layui/css/layui.css  rel=‘stylesheet’ />');document.write('<'+'script src=../Scripts/jquery-3.3.1.js></'+'script > ');document.write('<'+'script src=../Content/XAdmin/lib/layui/layui.all.js></'+'script > ');document.write('<'+'script src=../Scripts/Public.js></'+'script > ');</script><script>ShowMesCloseWindows('" + mes + "');</script>";
            return RecordNotExist;
        }
        #endregion


        /// <summary>
        /// 审批泛型方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="p"></param>
        /// <param name="userid"></param>
        /// <param name="IsRight"></param>
        /// <param name="auditRule"></param>
        /// <param name="message"></param>
        /// <param name="Comment"></param>
        public static void PublicAudit<T>(T p, int userId, ref bool IsRight, AuditRule auditRule, Model.Tool.Message message, string Comment) where T : PublicAudit
        {
            var name = GetUsers(userId).UserName;
            if (p.State == (int)AuditStateEnum.WaitApprove)
            {
                if (userId == auditRule.AuditUserId1)
                {
                    IsRight = true;//用于判断是否拥有审批权限
                    p.State = (int)AuditStateEnum.One;
                    p.AuditUserId1 = userId;
                    p.AuditTime1 = DateTime.Now;
                    p.AuditComment1 = Comment;
                    message.Remark = name;
                    message.IsSuccess = true;
                    message.Msg = "审批完成";
                }
            }
            else if (p.State == (int)AuditStateEnum.One)
            {
                if (userId == auditRule.AuditUserId2)
                {
                    IsRight = true;//用于判断是否拥有审批权限
                    p.State = (int)AuditStateEnum.Two;
                    p.AuditUserId2 = userId;
                    p.AuditTime2 = DateTime.Now;
                    p.AuditComment2 = Comment;
                    message.Remark = name;
                    message.IsSuccess = true;
                    message.Msg = "审批完成";
                }
            }
            else if (p.State == (int)AuditStateEnum.Two)
            {
                if (userId == auditRule.AuditUserId3)
                {
                    IsRight = true;//用于判断是否拥有审批权限
                    p.State = (int)AuditStateEnum.Three;
                    p.AuditUserId3 = userId;
                    p.AuditTime3 = DateTime.Now;
                    p.AuditComment3 = Comment;
                    message.Remark = name;
                    message.IsSuccess = true;
                    message.Msg = "审批完成";
                }
            }
            else if (p.State == (int)AuditStateEnum.Three)
            {
                if (userId == auditRule.AuditUserId4)
                {
                    IsRight = true;//用于判断是否拥有审批权限
                    p.State = (int)AuditStateEnum.Four;
                    p.AuditUserId4 = userId;
                    p.AuditTime4 = DateTime.Now;
                    p.AuditComment4 = Comment;
                    message.Remark = name;
                    message.IsSuccess = true;
                    message.Msg = "审批完成";
                }
            }
            else if (p.State == (int)AuditStateEnum.Four)
            {
                if (userId == auditRule.AuditUserId5)
                {
                    IsRight = true;//用于判断是否拥有审批权限
                    p.State = (int)AuditStateEnum.Five;
                    p.AuditUserId5 = userId;
                    p.AuditTime5 = DateTime.Now;
                    p.AuditComment5 = Comment;
                    message.Remark = name;
                    message.IsSuccess = true;
                    message.Msg = "审批完成";
                }
            }
            else if (p.State == (int)AuditStateEnum.Five)
            {
                if (userId == auditRule.AuditUserId6)
                {
                    IsRight = true;//用于判断是否拥有审批权限
                    p.State = (int)AuditStateEnum.Six;
                    p.AuditUserId6 = userId;
                    p.AuditTime6 = DateTime.Now;
                    p.AuditComment6 = Comment;
                    message.Remark = name;
                    message.IsSuccess = true;
                    message.Msg = "审批完成";
                }
            }
            bool IsAuditEndNew = p.State == Math.Pow(2, auditRule.AuditPeopleNumber) ? true : false;
            if (IsAuditEndNew)
            {
                p.IsAuditEnd = true;
            }
        }

        /// <summary>
        /// 递归获取所有在职状态的人员
        /// </summary>
        /// <param name="a"></param>
        /// <returns></returns>
        public static List<string> getalluser(string access_token, int a)
        {
            List<string> lis = new List<string>();
            IDingTalkClient client = new DingTalk.Api.DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/queryonjob");
            OapiSmartworkHrmEmployeeQueryonjobRequest req = new OapiSmartworkHrmEmployeeQueryonjobRequest();
            req.StatusList = "3,-1";
            req.Offset = a;
            req.Size = 20;
            OapiSmartworkHrmEmployeeQueryonjobResponse rsp = client.Execute(req, access_token);
            JObject obj = (JObject)JsonConvert.DeserializeObject(rsp.Body);
            var data = obj["result"]["data_list"].ToList();
            foreach (var item in data)
            {
                lis.Add(item.ToString());
            }
            try
            {
                if (obj["result"]["next_cursor"] != null)
                {
                    a += 20;
                    foreach (var item in getalluser(access_token, a))
                    {
                        lis.Add(item);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            return lis;
        }











        /// <summary>
        /// 企业在职员工userid列表
        /// </summary>
        /// <returns></returns>
        public static void getuserlis()
        {
            List<string> list = new List<string>();
            var lis = getalluser(access.access_token, 0);
            List<string> newlis = new List<string>();

            int counta = (lis.Count / 20) + (lis.Count % 20 == 0 ? 0 : 1);
            for (int i = 0; i < counta; i++)
            {
                string alis = "";
                var newlista = lis.Skip(i * 20).Take(20).ToList();
                foreach (var item in newlista)
                {
                    alis += item + ",";
                }
                alis = alis.Substring(0, alis.Length - 1);
                newlis.Add(alis);
            }
            List<AttendanceSheetDD> sheetlis = new List<AttendanceSheetDD>();
            foreach (var item in newlis)
            {
                var sheet = employeelist(access.access_token, item);
                foreach (var ite in sheet)
                {
                    sheetlis.Add(ite);
                }
            }
            access.attendances = sheetlis;

        }

        /// <summary>
        /// 批量获取员工花名册字段信息 
        /// </summary>
        /// <returns></returns>
        public static List<AttendanceSheetDD> employeelist(string access_token, string userlis)
        {
            var newuserlis = userlis.Split(',');
            List<AttendanceSheetDD> sheetlis = new List<AttendanceSheetDD>();
            bool result = false;
            try
            {
                IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/list");
                OapiSmartworkHrmEmployeeListRequest req = new OapiSmartworkHrmEmployeeListRequest();
                req.UseridList = userlis;
                OapiSmartworkHrmEmployeeListResponse rsp = client.Execute(req, access_token);
                JObject obj = (JObject)JsonConvert.DeserializeObject(rsp.Body);
                result = Convert.ToInt32(obj["errcode"]) == 0 ? true : false;

                var data = obj["result"].ToList();
                foreach (var item in data)
                {
                    var a = item["field_list"].ToList();
                    AttendanceSheetDD sheet = new AttendanceSheetDD();
                    for (int i = 0; i < a.Count; i++)
                    {
                        if (a[i]["field_code"].ToString() == "sys00-name")
                        {
                            sheet.UserName = a[i]["value"].ToString();
                        }
                        if (a[i]["field_code"].ToString() == "sys00-dept")
                        {
                            sheet.DepartmentName = a[i]["value"].ToString();
                        }
                        if (a[i]["field_code"].ToString() == "sys00-deptIds")
                        {
                            sheet.DepartmentId = a[i]["value"].ToString();
                        }
                        //if (a[i]["fieldCode"].ToString() == "sys00-position")
                        //{
                        //    sheet.JobNumber = a[i]["value"].ToString();
                        //}
                    }
                    sheet.UserNumber = item["userid"].ToString();
                    sheetlis.Add(sheet);
                }
                return sheetlis;
            }
            catch (Exception)
            {
                return sheetlis;
            }
        }

        /// <summary>
        /// 通过姓名获取钉钉中对应的每个人的id
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string UserIdByName(string name)
        {
            var namelis = name.Split(',');
            string id = "";
            foreach (var item in namelis)
            {
                foreach (var ite in access.attendances)
                {
                    if (ite.UserName == item)
                    {
                        id += ite.UserNumber + ",";
                    }
                }
            }
            if (id != "")
            {
                if (id.Substring(id.Length - 1, 1) == "," ? true : false)
                {
                    id = id.Substring(0, id.Length - 1);
                }
            }
            return id;
        }

        //#region 钉钉获取某一天考情数据导入数据库
        ///// <summary>
        ///// 获取打卡数据
        ///// </summary>
        ///// <returns></returns>
        //public bool clockin(string from_date)
        //{
        //    try
        //    {
        //        string data = "";
        //        List<punchclock> clist = new List<punchclock>();
        //        from_date = from_date + " 00:00:00";
        //        //string from_date = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day - 1).ToString("yyyy-MM-dd 00:00:00");               
        //        string to_date = Convert.ToDateTime(from_date).AddDays(1).ToString("yyyy-MM-dd 00:00:00");

        //        var uselis = db.Users.Where(x => x.Delete == false).ToList();
        //        var list = "";
        //        foreach (var item in uselis)
        //        {
        //            if (item.DD_number != "")
        //            {
        //                list += item.DD_number + ",";
        //                clist.Add(new punchclock(item.DD_number, Convert.ToDateTime(from_date)));
        //            }
        //        }
        //        List<string> lisstring = new List<string>();
        //        var lis = list.Substring(0, list.Length - 1).Split(',').ToList();
        //        int fountcount = (lis.Count / 50) + (lis.Count % 50 == 0 ? 0 : 1);
        //        for (int i = 0; i < fountcount; i++)
        //        {
        //            var newlis = lis.Skip(i * 50).Take(50).ToList();
        //            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/attendance/listRecord");
        //            OapiAttendanceListRecordRequest req = new OapiAttendanceListRecordRequest();
        //            req.UserIds = newlis;
        //            req.CheckDateFrom = from_date;
        //            req.CheckDateTo = to_date;
        //            OapiAttendanceListRecordResponse rsp = client.Execute(req, access.access_token);
        //            JToken objres = (JToken)JsonConvert.DeserializeObject(rsp.Body);
        //            if (objres["errcode"].ToString() == "0")
        //            {
        //                lisstring.Add(objres["recordresult"].ToString());
        //            }
        //        }
        //        if (lisstring.Count < 2)
        //        {
        //            data += lisstring[0];
        //        }
        //        if (lisstring.Count == 2)
        //        {
        //            lisstring[0] = lisstring[0].Substring(0, lisstring[0].Length - 1) + ",";
        //            lisstring[1] = lisstring[1].Substring(1, lisstring[1].Length - 1);
        //            data += lisstring[0] + lisstring[1];
        //        }
        //        if (lisstring.Count > 2)
        //        {
        //            var newjsonstring = "";
        //            for (int i = 0; i < lisstring.Count; i++)
        //            {
        //                if (i == 0)
        //                {
        //                    lisstring[i] = lisstring[i].Substring(lisstring[i].Length - 1, 1) + ",";
        //                }
        //                else if (i == lisstring.Count - 1)
        //                {
        //                    lisstring[i] = lisstring[i].Substring(0, lisstring[i].Length - 1);
        //                }
        //                else
        //                {
        //                    lisstring[i] = lisstring[i].Substring(lisstring[i].Length - 1, 1);
        //                    lisstring[i] = lisstring[i].Substring(0, lisstring[i].Length - 1) + ",";
        //                }
        //                newjsonstring += lisstring[i];
        //            }
        //            data += newjsonstring;
        //        }
        //        JToken @object = (JToken)JsonConvert.DeserializeObject(data);
        //        var clickresult = clockinresult(from_date);//打卡结果数据
        //        foreach (var item in clickresult)
        //        {
        //            if (item.ToString() != "")
        //            {
        //                for (int i = 0; i < clist.Count; i++)
        //                {
        //                    if (clist[i].number_DD == item["userId"].ToString())
        //                    {
        //                        JObject proc = (JObject)item;
        //                        bool procres = proc.Property("procInstId") != null ? true : false;
        //                        if (procres)
        //                        {
        //                            string procInstId = item["procInstId"].ToString();
        //                            JToken proresult = processinstance(procInstId);
        //                            if (proresult["result"].ToString() == "agree")
        //                            {
        //                                string type = proresult["title"].ToString().Substring(proresult["title"].ToString().Length - 2, 2);
        //                                switch (type)
        //                                {
        //                                    case "请假":
        //                                        clist[i].leaved = true;
        //                                        switch (proresult["form_component_values"][0]["value"].ToString())
        //                                        {
        //                                            case "事假":
        //                                                clist[i].leavetype = (int)LeaveEnum.compassionate_leave;
        //                                                break;
        //                                            case "病假":
        //                                                clist[i].leavetype = (int)LeaveEnum.sick_leave;
        //                                                break;
        //                                            case "年假":
        //                                                clist[i].leavetype = (int)LeaveEnum.annual_leave;
        //                                                break;
        //                                            case "婚假":
        //                                                clist[i].leavetype = (int)LeaveEnum.marriage_holiday;
        //                                                break;
        //                                            case "生育假":
        //                                                clist[i].leavetype = (int)LeaveEnum.Maternity_leave;
        //                                                break;
        //                                            case "陪产假":
        //                                                clist[i].leavetype = (int)LeaveEnum.Paternity_leave;
        //                                                break;
        //                                            case "丧假":
        //                                                clist[i].leavetype = (int)LeaveEnum.Bereavement_leave;
        //                                                break;
        //                                            case "工伤假":
        //                                                clist[i].leavetype = (int)LeaveEnum.Industrial_injury_leave;
        //                                                break;
        //                                        }
        //                                        JToken tok = (JToken)JsonConvert.DeserializeObject(proresult["form_component_values"][1]["value"].ToString());
        //                                        clist[i].leave_Starttime = tok[0].ToString();
        //                                        clist[i].leave_Endtime = tok[1].ToString();
        //                                        if (clist[i].leave_Starttime.Split(' ')[0] != clist[i].leave_Endtime.Split(' ')[0])
        //                                        {
        //                                            UpdataLeaved(clist[i]);
        //                                        }
        //                                        break;
        //                                    case "出差":
        //                                        clist[i].businesstravel = proresult["form_component_values"][2]["value"].ToString() + " " + proresult["form_component_values"][1]["name"].ToString() + " " + proresult["form_component_values"][1]["value"].ToString();
        //                                        break;
        //                                }
        //                            }
        //                        }
        //                        //#region 获取打卡的时间数据,部分打卡没有记录但存在结果
        //                        //if (item["timeResult"].ToString() == "NotSigned")
        //                        //{
        //                        //    clist[i].lackOfCards = true;
        //                        //    clist[i].lackOfCardscount += 1;
        //                        //}
        //                        //if (clist[i].lackOfCardscount > 1)
        //                        //{
        //                        //    if (!clist[i].leaved)
        //                        //    {
        //                        //        clist[i].absenteeism = true;
        //                        //        clist[i].lackOfCards = false;
        //                        //    }
        //                        //}
        //                        //#endregion

        //                    }
        //                }
        //                foreach (var ite in @object)
        //                {
        //                    JObject asd = (JObject)item;
        //                    bool zxc = asd.Property("recordId") != null ? true : false;
        //                    if (zxc)
        //                    {
        //                        if (item["recordId"].ToString() == ite["id"].ToString())
        //                        {
        //                            for (int i = 0; i < clist.Count; i++)
        //                            {
        //                                if (clist[i].number_DD == item["userId"].ToString())
        //                                {
        //                                    Apunchclock(ite, clist[i]);
        //                                }
        //                            }
        //                        }
        //                    }
        //                }
        //            }
        //        }
        //        GetApproval(from_date);

        //        businesstravelday(clist, from_date);//处理半天出差的情况问题

        //        delectsame(from_date, to_date);//排除已有的数据

        //        ListToDataTable(clist, "punchclock");
        //        //DataTable dt = SQLBuder.ListToDataTable(clist);
        //        //dt.TableName = "punchclock";
        //        //SQLBuder.InsertByDataTable(dt);
        //        return true;
        //    }
        //    catch (Exception ex)
        //    {
        //        LogHelper.LogWarning($"{DateTime.Now} ×××××××钉钉考情数据获取失败×××××××" + ex.Message);
        //        return false;
        //    }
        //    //数据库批量导入

        //}


        ///// <summary>
        ///// 获取打卡结果数据
        ///// </summary>
        ///// <returns></returns>
        //public JToken clockinresult(string from_date)
        //{
        //    string data = "";
        //    var list = "";
        //    var uselis = db.Users.Where(x => x.Delete == false).ToList();
        //    foreach (var item in uselis)
        //    {
        //        list += item.DD_number + ",";
        //    }
        //    List<string> lisstring = new List<string>();
        //    var lis = list.Substring(0, list.Length - 1).Split(',').ToList();
        //    int fountcount = (lis.Count / 50) + (lis.Count % 50 == 0 ? 0 : 1);
        //    for (int i = 0; i < fountcount; i++)
        //    {
        //        var newlis = lis.Skip(i * 50).Take(50).ToList();
        //        for (int k = 0; k < 2; k++)
        //        {

        //            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/attendance/list");
        //            OapiAttendanceListRequest req = new OapiAttendanceListRequest();
        //            req.WorkDateFrom = from_date;
        //            req.WorkDateTo = from_date;
        //            req.UserIdList = newlis;
        //            req.Offset = k * 50 + k;
        //            req.Limit = 50;
        //            OapiAttendanceListResponse rsp = client.Execute(req, access.access_token);
        //            JToken objres = (JToken)JsonConvert.DeserializeObject(rsp.Body);
        //            if (objres["errcode"].ToString() == "0")
        //            {
        //                lisstring.Add(objres["recordresult"].ToString());
        //            }
        //        }
        //    }
        //    if (lisstring.Count < 2)
        //    {
        //        data += lisstring[0];
        //    }
        //    if (lisstring.Count == 2)
        //    {
        //        lisstring[0] = lisstring[0].Substring(0, lisstring[0].Length - 1) + ",";
        //        lisstring[1] = lisstring[1].Substring(1, lisstring[1].Length - 1);
        //        data += lisstring[0] + lisstring[1];
        //    }
        //    if (lisstring.Count > 2)
        //    {
        //        var newjsonstring = "";
        //        for (int i = 0; i < lisstring.Count; i++)
        //        {
        //            if (i == 0)
        //            {
        //                lisstring[i] = lisstring[i].Substring(0, lisstring[i].Length - 1) + ",";
        //            }
        //            else if (i == lisstring.Count - 1)
        //            {
        //                lisstring[i] = lisstring[i].Substring(1, lisstring[i].Length - 1);
        //            }
        //            else
        //            {
        //                lisstring[i] = lisstring[i].Substring(1, lisstring[i].Length - 1);
        //                lisstring[i] = lisstring[i].Substring(0, lisstring[i].Length - 1) + ",";
        //            }
        //            newjsonstring += lisstring[i];
        //        }
        //        data += newjsonstring;
        //    }
        //    JToken @object = (JToken)JsonConvert.DeserializeObject(data);
        //    object objdata = JsonConvert.DeserializeObject(data);
        //    return @object;
        //}



        ///// <summary>
        ///// 获取审批单数据
        ///// </summary>
        ///// <param name="processInstanceId"></param>
        ///// <returns></returns>
        //public JToken processinstance(string processInstanceId)
        //{
        //    bool result = false;
        //    IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/get");
        //    OapiProcessinstanceGetRequest req = new OapiProcessinstanceGetRequest();
        //    req.ProcessInstanceId = processInstanceId;
        //    OapiProcessinstanceGetResponse rsp = client.Execute(req, access.access_token);
        //    JToken objres = (JToken)JsonConvert.DeserializeObject(rsp.Body);
        //    result = objres["errcode"].ToString() == "0" ? true : false;
        //    return objres["process_instance"];
        //}





        ///// <summary>
        ///// 修改请假
        ///// </summary>
        ///// <param name="pun"></param>
        //public void UpdataLeaved(punchclock pun)
        //{
        //    string sql = "UPDATE `punchclock` SET `leaved`='1',`leavetype`='" + pun.leavetype + "' WHERE '" + pun.leave_Starttime + "' <=`onclicktime` AND  `onclicktime`<= '" + pun.leave_Endtime + "' AND `number_DD`='" + pun.number_DD + "'";
        //    updataleaved(sql);
        //}



        ///// <summary>
        ///// 通过打卡记录获取位置和迟到早退的数据处理
        ///// </summary>
        ///// <param name="ite"></param>
        ///// <param name="pun"></param>
        //public void Apunchclock(JToken ite, punchclock pun)
        //{
        //    string regex = ".*成都市+.*";
        //    if (ite["checkType"].ToString() == "OnDuty")
        //    {
        //        if (((JObject)ite).Property("userAddress") != null)
        //        {
        //            pun.onclickaddress = ite["userAddress"].ToString();
        //            if (Regex.IsMatch(pun.onclickaddress, regex) && ite["locationResult"].ToString() == "Normal")//打卡位置包含成都市或者在规定范围内将取消出差的状体
        //            {
        //                pun.businesstravel = "";
        //            }
        //        }
        //        pun.onclicktime = ConvertLongToDateTime(ite["userCheckTime"].ToString());
        //    }
        //    if (ite["checkType"].ToString() == "OffDuty")
        //    {
        //        if (((JObject)ite).Property("userAddress") != null)
        //        {
        //            pun.downclickaddress = ite["userAddress"].ToString();
        //            if (Regex.IsMatch(pun.downclickaddress, regex) && ite["locationResult"].ToString() == "Normal")//打卡位置包含成都市或者在规定范围内将取消出差的状体
        //            {
        //                pun.businesstravel = "";
        //            }
        //        }
        //        pun.downclicktime = ConvertLongToDateTime(ite["userCheckTime"].ToString());
        //    }
        //    if (pun.businesstravel == "" || pun.businesstravel == null)
        //    {
        //        switch (ite["timeResult"].ToString())
        //        {
        //            case "Early":
        //                pun.leaveearly = true;
        //                pun.leaveearlytime = (Convert.ToDecimal(ite["baseCheckTime"]) - Convert.ToDecimal(ite["userCheckTime"])).ToString();
        //                break;
        //            case "Late":
        //                pun.late = true;
        //                pun.latetime = (Convert.ToDecimal(ite["userCheckTime"]) - Convert.ToDecimal(ite["baseCheckTime"])).ToString();
        //                break;
        //        }
        //    }
        //}

        ///// <summary>
        ///// 获取加班审批
        ///// </summary>
        ///// <param name="userlis"></param>
        ///// <param name="from_date"></param>
        ///// <returns></returns>
        //public async void GetApproval(string from_date)
        //{

        //    bool result = false;
        //    List<Addworked> lisw = new List<Addworked>();
        //    string jiajiari = await IsHolidayByDate(from_date);
        //    DateTime time = Convert.ToDateTime(from_date);
        //    DateTime timeend = time.AddDays(1);
        //    long start = (time.ToUniversalTime().Ticks - 621355968000000000) / 10000;
        //    long end = (timeend.ToUniversalTime().Ticks - 621355968000000000) / 10000;
        //    IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/listids");
        //    OapiProcessinstanceListidsRequest req = new OapiProcessinstanceListidsRequest();
        //    req.ProcessCode = "PROC-FF6YHERSO2-ONWB4T0HR7AYB1ETQ88K2-NGHIH4QI-BA";//加班
        //    req.StartTime = start;
        //    req.EndTime = end;
        //    OapiProcessinstanceListidsResponse rsp = client.Execute(req, access.access_token);
        //    JToken obj = (JToken)JsonConvert.DeserializeObject(rsp.Body);
        //    result = obj["errcode"].ToString() == "0" ? true : false;
        //    if (obj["result"]["list"].ToString() != "" && obj["result"]["list"].ToString() != null)
        //    {
        //        foreach (var item in obj["result"]["list"])
        //        {
        //            JToken tok = processinstance(item.ToString());

        //            if (tok["status"].ToString() == "COMPLETED")
        //            {
        //                string timed = tok["form_component_values"][0]["value"].ToString().Replace('"', ' ');
        //                timed = timed.Substring(0, timed.Length - 1);
        //                timed = timed.Substring(1, timed.Length - 1);

        //                DateTime t1 = Convert.ToDateTime(timed.Split(',')[0].ToString().Trim());
        //                DateTime t2 = Convert.ToDateTime(timed.Split(',')[1].ToString().Trim());
        //                #region 判断提交的加班在不在同一天的情况               
        //                if (t1.Date != t2.Date)
        //                {
        //                    TimeSpan daydate = t2.Date - t1.Date;
        //                    for (int i = 0; i <= daydate.Days; i++)
        //                    {
        //                        DateTime addwotkdate = t1.AddDays(i);

        //                        var olddata = db.addworked.Where(x => x.todaytime == addwotkdate.Date).ToList();
        //                        foreach (var workold in olddata)
        //                        {
        //                            db.addworked.Remove(workold);
        //                            db.SaveChanges();
        //                        }

        //                        Addworked work2 = new Addworked();
        //                        work2.addwork = true;
        //                        work2.number_DD = tok["originator_userid"].ToString();
        //                        work2.addworktype = await IsHolidayByDate(addwotkdate.ToString("yyyy-MM-dd mm:dd:ss"));
        //                        if (i == 0)
        //                        {
        //                            if (t1.Hour > 12)
        //                            {
        //                                work2.addwork_Starttime = addwotkdate.ToString("yyyy-MM-dd 13:30:00");
        //                                work2.addwork_Endtime = addwotkdate.ToString("yyyy-MM-dd 17:30:00");
        //                                work2.addworktime = "4";
        //                            }
        //                            else
        //                            {
        //                                work2.addwork_Starttime = addwotkdate.ToString("yyyy-MM-dd mm:dd:ss");
        //                                work2.addwork_Endtime = addwotkdate.ToString("yyyy-MM-dd 17:30:00");
        //                                work2.addworktime = "8";
        //                            }
        //                        }
        //                        if (i == daydate.Days)
        //                        {
        //                            if (t2.Hour > 13)
        //                            {
        //                                work2.addwork_Endtime = addwotkdate.ToString("yyyy-MM-dd 17:30:00");
        //                                work2.addworktime = "8";
        //                            }
        //                            else
        //                            {
        //                                work2.addwork_Endtime = t2.ToString("yyyy-MM-dd mm:dd:ss");
        //                                work2.addworktime = "4";
        //                            }
        //                        }
        //                        work2.addwork_Starttime = addwotkdate.ToString("yyyy-MM-dd 08:30:00");
        //                        work2.addwork_Endtime = addwotkdate.ToString("yyyy-MM-dd 17:30:00");
        //                        work2.addworktime = "8";
        //                        work2.todaytime = addwotkdate.Date;
        //                        lisw.Add(work2);
        //                    }
        //                }
        //                #endregion
        //                else
        //                {
        //                    var olddata = db.addworked.Where(x => x.todaytime == t1.Date).ToList();
        //                    foreach (var workold in olddata)
        //                    {
        //                        db.addworked.Remove(workold);
        //                        db.SaveChanges();
        //                    }

        //                    Addworked work = new Addworked();
        //                    var a = timed.Split(',')[0].Trim().Split(' ')[0];
        //                    var b = from_date.Split(' ')[0];
        //                    if (a == b)
        //                    {
        //                        work.addworktype = jiajiari;
        //                    }
        //                    else
        //                    {
        //                        work.addworktype = await IsHolidayByDate(a);
        //                    }
        //                    work.addwork_Starttime = timed.Split(',')[0].ToString().Trim();
        //                    work.addwork_Endtime = timed.Split(',')[1].ToString().Trim();

        //                    work.number_DD = tok["originator_userid"].ToString();
        //                    work.addworktime = tok["form_component_values"][1]["value"].ToString();

        //                    work.todaytime = t1.Date;
        //                    work.addwork = true;

        //                    lisw.Add(work);
        //                }
        //            }
        //        }
        //    }
        //    if (lisw.Count > 0)
        //    {
        //        ListToDataTable(lisw, "addworked");
        //    }
        //}

        ///// <summary>
        ///// 处理出差(包括半天)的情况问题,外加缺卡和旷工的数据处理
        ///// </summary>
        ///// <param name="clist"></param>
        //public void businesstravelday(List<punchclock> clist, string from_date)
        //{
        //    try
        //    {
        //        foreach (var item in clist)
        //        {
        //            string regex = ".*成都市+.*";
        //            string regex2 = ".*固远晨通+.*";
        //            if ((item.onclickaddress != "" && item.onclickaddress != null) && (item.downclickaddress != "" && item.downclickaddress != null))
        //            {
        //                int morning = (Regex.IsMatch(item.onclickaddress, regex) || Regex.IsMatch(item.onclickaddress, regex2)) == true ? 0 : 1;
        //                int afternoon = (Regex.IsMatch(item.downclickaddress, regex) || Regex.IsMatch(item.downclickaddress, regex2)) == true ? 0 : 1;

        //                switch (morning + afternoon)
        //                {
        //                    case 1:
        //                        item.businesstravelday = "0.5";
        //                        break;
        //                    case 2:
        //                        item.businesstravelday = "1";
        //                        break;
        //                }
        //            }


        //            int card_morning = item.onclicktime == null ? 1 : 0;
        //            int card_afternoon = item.downclicktime == null ? 1 : 0;
        //            switch (card_morning + card_afternoon)
        //            {
        //                case 1:
        //                    item.lackOfCards = true;
        //                    item.lackOfCardscount = 1;
        //                    break;
        //                case 2:
        //                    item.absenteeism = true;
        //                    break;
        //            }
        //            if (item.leaved)
        //            {
        //                List<string> numlis = new List<string>();
        //                numlis.Add(item.number_DD);
        //                IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/attendance/list");
        //                OapiAttendanceListRequest req = new OapiAttendanceListRequest();
        //                req.WorkDateFrom = from_date;
        //                req.WorkDateTo = from_date;
        //                req.UserIdList = numlis;
        //                req.Offset = 0;
        //                req.Limit = 10;
        //                OapiAttendanceListResponse rsp = client.Execute(req, access.access_token);
        //                JToken objres = (JToken)JsonConvert.DeserializeObject(rsp.Body);
        //                var data = (JToken)JsonConvert.DeserializeObject(objres["recordresult"].ToString());

        //                int procres = 0;
        //                for (int i = 0; i < data.Count(); i++)
        //                {
        //                    JObject proc = (JObject)data[i];
        //                    if (proc.Property("procInstId") != null ? true : false)
        //                    {
        //                        procres++;
        //                    }
        //                }
        //                if (procres == 1)
        //                {
        //                    item.leavedday = "0.5";
        //                }
        //                if (procres == 2)
        //                {
        //                    item.lackOfCards = false;
        //                    item.lackOfCardscount = 0;
        //                    item.absenteeism = false;
        //                    item.leavedday = "1";
        //                }
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {

        //        throw;
        //    }

        //}


        //public static void delectsame(string time1, string time2)
        //{
        //    using (MySqlConnection conn = new MySqlConnection(strcon))
        //    {
        //        string sql = "DELETE FROM `punchclock` WHERE `punchclock`.`todaytime`>='" + time1 + "' AND `punchclock`.`todaytime`<='" + time2 + "'";
        //        conn.Open();
        //        MySqlCommand comm = new MySqlCommand(sql, conn);
        //        comm.ExecuteNonQuery();
        //        conn.Close();
        //    }
        //}

        ///// <summary>
        ///// List 转化 DataTable
        ///// </summary>
        ///// <typeparam name="T"></typeparam>
        ///// <param name="list"></param>
        ///// <param name="tablename"></param>
        //public static void ListToDataTable<T>(List<T> list, string tablename)
        //{
        //    Type tp = typeof(T);
        //    PropertyInfo[] proInfos = tp.GetProperties();
        //    DataTable dt = new DataTable();
        //    foreach (var item in proInfos)
        //    {
        //        //解决DataSet不支持System.Nullable<>问题
        //        Type colType = item.PropertyType;
        //        if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
        //        {
        //            colType = colType.GetGenericArguments()[0];
        //        }
        //        //添加列明及对应类型  
        //        dt.Columns.Add(item.Name, colType);
        //    }
        //    foreach (var item in list)
        //    {
        //        DataRow dr = dt.NewRow();
        //        foreach (var proInfo in proInfos)
        //        {
        //            object obj = proInfo.GetValue(item);
        //            if (obj == null)
        //            {
        //                continue;
        //            }
        //            if (proInfo.PropertyType == typeof(DateTime) && Convert.ToDateTime(obj) < Convert.ToDateTime("1753-01-01"))
        //            {
        //                continue;
        //            }
        //            dr[proInfo.Name] = obj;
        //        }
        //        dt.Rows.Add(dr);
        //    }
        //    dt.TableName = tablename;
        //    InsertByDataTable(dt);
        //    //return dt;
        //}
        ///// <summary>
        ///// 修改请假的状态
        ///// </summary>
        ///// <param name="sql"></param>
        //public static void updataleaved(string sql)
        //{

        //    string strcon = ConfigurationHelper.GetConfigValueByKey("ConnectionStrings:DefaultConnection");
        //    using (MySqlConnection conn = new MySqlConnection(strcon))
        //    {
        //        conn.Open();
        //        MySqlCommand comm = new MySqlCommand(sql, conn);
        //        comm.ExecuteNonQuery();
        //        conn.Close();
        //    }
        //}
        ///// <summary>        
        ///// 时间戳转为C#格式时间        
        ///// </summary>        
        ///// <param name=”timeStamp”></param>        
        ///// <returns></returns>        
        //public string ConvertLongToDateTime(string timeStamp)
        //{
        //    if (timeStamp != "")
        //    {
        //        DateTime dtStart = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1, 8, 0, 0, 0), TimeZoneInfo.Local);
        //        long lTime = long.Parse(timeStamp) * 10000;
        //        TimeSpan toNow = new TimeSpan(lTime);
        //        return dtStart.Add(toNow).ToString("yyyy-MM-dd HH:mm:ss");
        //    }
        //    else
        //    {
        //        return " ";
        //    }
        //}


        ///// <summary>
        ///// 判断是不是周末/节假日/工作日
        ///// </summary>
        ///// <param name="date">日期字符串</param>
        ///// <returns></returns>
        //public async Task<string> IsHolidayByDate(string date)
        //{
        //    var webClient = new System.Net.WebClient();
        //    string resul = "";
        //    var day = date.Split(' ')[0];
        //    day = day.Replace("-", "");
        //    var PostVars = new System.Collections.Specialized.NameValueCollection
        //    {
        //        { "d", day},//参数
        //        { "apikey","violetzll" }
        //    };
        //    try
        //    {
        //        //0为工作日，1为周末，2为法定节假日
        //        var byteResult = await webClient.UploadValuesTaskAsync("http://vip.bitefu.net/jiari/", "POST", PostVars);//请求地址,传参方式,参数集合
        //        var asda = (JToken)JsonConvert.DeserializeObject(Encoding.UTF8.GetString(byteResult));//获取返回值
        //        resul += asda["data"] + "";
        //    }
        //    catch (Exception ex)
        //    {

        //    }
        //    return resul;
        //}




        ///// <summary>
        ///// DataTable批量加入MYSQL数据库
        ///// </summary>
        ///// <param name="dataTable"></param>
        ///// <returns></returns>
        //public static async void InsertByDataTable(DataTable dataTable)
        //{
        //    string result = string.Empty;
        //    if (null == dataTable || dataTable.Rows.Count <= 0)
        //    {
        //        LogHelper.LogWarning($"{DateTime.Now} ×××××××添加失败！DataTable暂无数据!×××××××");
        //    }
        //    if (string.IsNullOrEmpty(dataTable.TableName))
        //    {
        //        LogHelper.LogWarning($"{DateTime.Now} ×××××××添加失败！请先设置DataTable的名称！×××××××");
        //    }
        //    // 构建INSERT语句
        //    LogHelper.LogInformation($"{DateTime.Now} ************************数据库数据添加开始！***********************");
        //    StringBuilder sb = new StringBuilder();
        //    sb.Append("INSERT INTO " + dataTable.TableName + "(");
        //    for (int i = 0; i < dataTable.Columns.Count; i++)
        //    {
        //        sb.Append(dataTable.Columns[i].ColumnName + ",");
        //    }
        //    sb.Remove(sb.ToString().LastIndexOf(','), 1);
        //    sb.Append(") VALUES ");
        //    for (int i = 0; i < dataTable.Rows.Count; i++)
        //    {
        //        sb.Append("(");
        //        for (int j = 0; j < dataTable.Columns.Count; j++)
        //        {
        //            sb.Append("'" + dataTable.Rows[i][j] + "',");
        //        }
        //        sb.Remove(sb.ToString().LastIndexOf(','), 1);
        //        sb.Append("),");
        //    }
        //    sb.Remove(sb.ToString().LastIndexOf(','), 1);
        //    sb.Append(";");
        //    int res = -1;
        //    string sql = sb.ToString().Replace("False", "0");
        //    sql = sql.Replace("True", "1");



        //    using (MySqlConnection con = new MySqlConnection(strcon))
        //    {
        //        con.Open();
        //        using (MySqlCommand cmd = new MySqlCommand(sql, con))
        //        {
        //            try
        //            {
        //                res = cmd.ExecuteNonQuery();
        //            }
        //            catch (Exception ex)
        //            {
        //                res = -1;
        //                // Unknown column 'names' in 'field list' 
        //                LogHelper.LogInformation($"{DateTime.Now} ×××××××钉钉考情数据添加数据库失败×××××××" + ex.Message);
        //            }
        //        }
        //    }
        //    if (res > 0)
        //    {
        //        LogHelper.LogInformation($"{DateTime.Now} ******************钉钉考情数据添加数据库添加成功!**********************");
        //    }
        //}
        ///// <summary>
        ///// 比较数据正确性
        ///// </summary>
        ///// <param name="NumberValues">数据源</param>
        ///// <param name="Values">比较值</param>
        ///// <returns></returns>
        //public bool Compare(string NumberValues, int Values)
        //{
        //    string[] numbers = NumberValues.Split(',');

        //    foreach (var item in numbers)
        //    {
        //        if (item == Values.ToString())
        //        {
        //            return true;
        //        }
        //    }
        //    return false;
        //}



        //#region 发送短信

        ///// <summary>
        ///// 构造签批通知的短信
        ///// </summary>
        ///// <param name="code">待验证的资源权限码，如果code为null，代表取传入用户部长的电话，为资源码，代表取当前资源码权限所属用户的电话</param>
        ///// <param name="name">待签批的单子类型名称，比如采购单、申购单</param>
        ///// <param name="number">待签批单子编号</param>
        //public static async Task BuildSendDeviceMesAsync(string code, int userid, string name, string number, bool isLeaderShip = false)
        //{
        //    try
        //    {
        //        string phone = string.Empty;
        //        //如果传过来的资源权限码为空，默认为应该寻找部长的电话号码，通知其审批
        //        if (string.IsNullOrEmpty(code))
        //        {
        //            int DepartmentId = db.Users.Where(y => y.Id == userid).FirstOrDefault().DepartmentId;
        //            if (isLeaderShip)
        //            {
        //                int LeaderShip = db.Department.Where(x => x.Id == DepartmentId).FirstOrDefault().LeaderShip;
        //                phone = db.Users.Where(y => y.Id == LeaderShip).FirstOrDefault().Phone;
        //            }
        //            else
        //            {
        //                int PartOwner = db.Department.Where(x => x.Id == DepartmentId).FirstOrDefault().PartOwner;
        //                phone = db.Users.Where(y => y.Id == PartOwner).FirstOrDefault().Phone;
        //            }
        //        }
        //        else
        //        {
        //            phone = GetPhoneByCode(code);
        //        }
        //        string username = db.Users.Where(y => y.Id == userid).FirstOrDefault().UserName;
        //        string[] Parm = { username, name, number };
        //        if (!string.IsNullOrEmpty(phone))
        //        {
        //            await SendMesAsync(phone, tpl_Purchase_id, Parm);
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        LogHelper.LogWarning(DateTime.Now.ToString("yyyy-MM-dd") + "短信消息推送失败!" + e.Message + "");
        //    }
        //}

        ///// <summary>
        ///// 构造项目报表签批通知的短信
        ///// </summary>
        ///// <param name="code">待验证的资源权限码，如果code为null，代表取传入用户部长的电话，为资源码，代表取当前资源码权限所属用户的电话</param>
        ///// <param name="projectId">项目id，根据此信息查找项目名称和编号信息</param>
        ///// <param name="projectReportType">当前审批的项目报表类型</param>
        ///// <param name="userid">如果需要此id的部长进行审批，则需要此信息</param>
        ///// <returns></returns>
        //public static async Task BuildSendProjectMesAsync(int projectId, string projectReportType, string code, int DepartmentId = 0, int HeadUserid = 0)
        //{
        //    try
        //    {
        //        string phone = string.Empty;
        //        //如果传过来的资源权限码为空，默认为应该寻找部长的电话号码，通知其审批
        //        if (string.IsNullOrEmpty(code))
        //        {
        //            if (DepartmentId != 0)
        //            {
        //                int PartOwner = db.Department.Where(x => x.Id == DepartmentId).FirstOrDefault().PartOwner;
        //                phone = db.Users.Where(y => y.Id == PartOwner).FirstOrDefault().Phone;
        //            }
        //            else if (HeadUserid != 0)
        //            {
        //                phone = db.Users.Where(y => y.Id == HeadUserid).FirstOrDefault().Phone;
        //            }
        //        }
        //        else
        //        {
        //            phone = GetPhoneByCode(code);
        //        }
        //        Project p = db.Project.Where(x => x.Id == projectId).FirstOrDefault();
        //        string[] Parm = { p.ProjectName, p.ProjectNumber, projectReportType };
        //        if (!string.IsNullOrEmpty(phone))
        //        {
        //            await SendMesAsync(phone, tpl_ProjectReport_id, Parm);
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        LogHelper.LogWarning(DateTime.Now.ToString("yyyy-MM-dd") + "项目报表短信消息推送失败!" + e.Message + "");
        //    }
        //}
        ///// <summary>
        ///// 构造项目物资库的签批通知的短信
        ///// </summary>
        ///// <param name="projectId">项目标识，根据项目id取出项目负责人的电话号码</param>
        ///// <param name="name">待签批的单子类型名称，比如采购单、申购单</param>
        ///// <param name="number">待签批单子编号</param>
        //public static async Task BuildSendProjectMaterialMesAsync(int projectId, int userid, string name, string number)
        //{
        //    try
        //    {
        //        string phone = string.Empty;
        //        string headUserid = db.Project.Where(y => y.Id == projectId).FirstOrDefault().HeadUserId;
        //        phone = db.Users.Where(x => x.Id == Convert.ToInt32(headUserid)).FirstOrDefault().Phone;
        //        string username = db.Users.Where(y => y.Id == userid).FirstOrDefault().UserName;
        //        string[] Parm = { username, name, number };
        //        if (!string.IsNullOrEmpty(phone))
        //        {
        //            await SendMesAsync(phone, tpl_Purchase_id, Parm);
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        LogHelper.LogWarning(DateTime.Now.ToString("yyyy-MM-dd") + "项目物资短信消息推送失败!" + e.Message + "");
        //    }
        //}
        //#endregion

        //#region OA消息推送接口
        ///// <summary>
        ///// OA消息推送(516927短信的消息通知)
        ///// </summary>
        ///// <param name="code">待验证的资源权限码，如果code为null，代表取传入用户部长的电话，为资源码，代表取当前资源码权限所属用户的电话</param></param>
        ///// <param name="userid">发送人Id</param>
        ///// <param name="typename">消息类型(申购单\采购单)</param>
        ///// <param name="number">(申购单\采购单)编号</param>
        ///// <returns></returns>
        //public static async Task BuildSendPurchaseMessageMesAsync(string code, int userid, string typename, string number, bool isLeaderShip = false)
        //{
        //    MessageTableController tab = new MessageTableController(db);
        //    try
        //    {
        //        string id = string.Empty;
        //        //如果传过来的资源权限码为空，默认为应该寻找部长的电话号码，通知其审批
        //        if (string.IsNullOrEmpty(code))
        //        {
        //            int DepartmentId = db.Users.Where(y => y.Id == userid).FirstOrDefault().DepartmentId;
        //            if (isLeaderShip)
        //            {
        //                int LeaderShip = db.Department.Where(x => x.Id == DepartmentId).FirstOrDefault().LeaderShip;
        //                id = db.Users.Where(y => y.Id == LeaderShip).FirstOrDefault().Id.ToString();
        //            }
        //            else
        //            {
        //                int PartOwner = db.Department.Where(x => x.Id == DepartmentId).FirstOrDefault().PartOwner;
        //                id = db.Users.Where(y => y.Id == PartOwner).FirstOrDefault().Id.ToString();
        //            }
        //        }
        //        else
        //        {
        //            id = GetIdByCode(code);
        //        }
        //        var username = db.Users.Where(x => x.Id == userid).FirstOrDefault().UserName;
        //        if (!string.IsNullOrEmpty(id))
        //        {
        //            string message = $"由" + username + "提交的" + typename + "需要您的审批,编号为" + number + ",请及时处理!";
        //            string url = "";
        //            switch (typename)
        //            {
        //                case "采购单":
        //                    url = "/Purchase/Index";
        //                    break;
        //                case "申购单":
        //                    url = "/Purchase/ApplyPurchase";
        //                    break;
        //                case "入库单":
        //                    url = "/Device/InboundOrder";
        //                    break;
        //                case "出库单":
        //                    url = "/Device/OutboundOrder";
        //                    break;
        //                case "归还单":
        //                    url = "/Device/ReturnOrder";
        //                    break;
        //                case "借款单":
        //                    url = "/Finance/FinanceLoan";
        //                    break;
        //                case "报销单":
        //                    url = "/Finance/FinanceReimbursement";
        //                    break;
        //                case "开票申请":
        //                    url = "/Finance/FinanceInvoice";
        //                    break;
        //            }
        //            var res = AddMessage(message, id, "1", url);                                                 
        //            await MessageMesAsync(userid.ToString(), message, id);
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        LogHelper.LogWarning(DateTime.Now.ToString("yyyy-MM-dd") + "；" + e.Message);
        //    }
        //}
        ///// <summary>
        ///// OA消息推送(568991短信的消息通知)
        ///// </summary>
        ///// <param name="code">待验证的资源权限码，如果code为null，代表取传入用户部长的电话，为资源码，代表取当前资源码权限所属用户的电话</param>
        ///// <param name="projectId">项目id，根据此信息查找项目名称和编号信息</param>
        ///// <param name="projectReportType">当前审批的项目报表类型</param>
        ///// <param name="userid">如果需要此id的部长进行审批，则需要此信息</param>
        //public static async Task BuildSendProjectReportMessageMesAsync(int projectid, string projectReportType, string code, int DepartmentId = 0, int HeadUserid = 0)
        //{
        //    MessageTableController tab = new MessageTableController(db);
        //    try
        //    {
        //        string id = string.Empty;
        //        //如果传过来的资源权限码为空，默认为应该寻找部长的电话号码，通知其审批
        //        if (string.IsNullOrEmpty(code))
        //        {
        //            if (DepartmentId != 0)
        //            {
        //                int PartOwner = db.Department.Where(x => x.Id == DepartmentId).FirstOrDefault().PartOwner;
        //                id = db.Users.Where(y => y.Id == PartOwner).FirstOrDefault().Id.ToString();
        //            }
        //            else if (HeadUserid != 0)
        //            {
        //                id = db.Users.Where(y => y.Id == HeadUserid).FirstOrDefault().Id.ToString();
        //            }
        //        }
        //        else
        //        {
        //            id = GetIdByCode(code);
        //        }
        //        Project p = db.Project.Where(x => x.Id == projectid).FirstOrDefault();
        //        if (!string.IsNullOrEmpty(id))
        //        {
        //            string message = $"名称" + p.ProjectName + "," + p.Id + "的项目" + projectReportType + "需要您的审批!";
        //            var res = AddMessage(message, id, "1", "/Project/Index");
        //            await MessageMesAsync(null, message, id);
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        LogHelper.LogWarning(DateTime.Now.ToString("yyyy-MM-dd") + "；" + e.Message);
        //    }
        //}
        //#endregion

        //#region 钉钉接口,在app上推送oa系统的消息
        ///// <summary>
        ///// 钉钉推送OA消息(516927短信的消息通知)
        ///// </summary>
        ///// <param name="code"></param>
        ///// <param name="userid">消息的发起者</param>
        ///// <param name="typename">消息类型</param>
        ///// <param name="number">编号</param>
        ///// <param name="ProjectId">项目id</param>
        ///// <param name="time">发起时间</param>
        ///// <param name="jsonstring">消息模板的接送内容</param>
        ///// <returns></returns>
        //public static async Task DingDingSendPurchaseMessageMesAsync(string code, int userid, string typename, string number, int ProjectId, DateTime? time, string jsonstring = "", bool isLeaderShip = false)
        //{
        //    try
        //    {
        //        string name = string.Empty;
        //        //如果传过来的资源权限码为空，默认为应该寻找部长的电话号码，通知其审批
        //        if (string.IsNullOrEmpty(code))
        //        {
        //            int DepartmentId = db.Users.Where(y => y.Id == userid).FirstOrDefault().DepartmentId;
        //            if (isLeaderShip)
        //            {
        //                int LeaderShip = db.Department.Where(x => x.Id == DepartmentId).FirstOrDefault().LeaderShip;
        //                name = db.Users.Where(y => y.Id == LeaderShip).FirstOrDefault().UserName;
        //            }
        //            else
        //            {
        //                int PartOwner = db.Department.Where(x => x.Id == DepartmentId).FirstOrDefault().PartOwner;
        //                name = db.Users.Where(y => y.Id == PartOwner).FirstOrDefault().UserName;
        //            }
        //        }
        //        else
        //        {
        //            name = GetNameByCode(code);
        //        }
        //        var username = db.Users.Where(x => x.Id == userid).FirstOrDefault();
        //        if (!string.IsNullOrEmpty(name))
        //        {
        //            string url = onlineurl;
        //            string message = $"由" + username.UserName + "提交的" + typename + "需要您的审批,编号为" + number + ",请及时处理!";
        //            if (jsonstring == "")
        //            {
        //                jsonstring += "{";
        //                var depname = db.Department.Where(x => x.Id == username.DepartmentId).FirstOrDefault().DepartmentName;
        //                var pro = db.Project.Where(x => x.Id == ProjectId).FirstOrDefault();
        //                jsonstring += "\"申请人\":\"" + depname + " " + username.UserName + "\",";
        //                if (time != null)
        //                {
        //                    jsonstring += "\"申请时间\":\"" + time + "\",";
        //                }
        //                if (pro != null)
        //                {
        //                    jsonstring += "\"项目\":\"" + pro.ProjectName + "\"";
        //                }
        //                jsonstring += "}";
        //            }
        //            var named = db.Users.Where(x => x.UserName == name).FirstOrDefault();
        //            switch (typename)
        //            {
        //                case "申购单":
        //                    url += "AppApproval/APP_ApplyPurchaseOrder?number=" + number + "&dd_id=" + named.DD_number + "";
        //                    break;
        //                case "采购单":
        //                    url += "AppApproval/APP_PurchaseOrder?number=" + number + "&dd_id=" + named.DD_number + "";
        //                    break;
        //                case "入库单":
        //                    url += "AppApproval/InboundOrder?number=" + number + "&dd_id=" + named.DD_number + "";
        //                    break;
        //                case "出库单":
        //                    url += "AppApproval/OutboundOrder?number=" + number + "&dd_id=" + named.DD_number + "";
        //                    break;
        //                case "归还单":
        //                    url += "AppApproval/ReturnOrder?number=" + number + "&dd_id=" + named.DD_number + "";
        //                    break;
        //                case "借款单":
        //                    url += "AppApproval/APP_FinanceLoanOrder?number=" + number + "&dd_id=" + named.DD_number + "";
        //                    break;
        //                case "报销单":
        //                    url += "AppApproval/APP_FinanceReimbursementOrder?number=" + number + "&dd_id=" + named.DD_number + "";
        //                    break;
        //                case "开票申请":
        //                    url += "AppApproval/APP_FinanceInvoiceOrder?number=" + number + "&dd_id=" + named.DD_number + "";
        //                    break;
        //            }
        //            await asyncsend_v2(named.DD_number, message, url, jsonstring);
        //            LogHelper.LogWarning(DateTime.Now.ToString("yyyy-MM-dd") + "  " + named.DD_number + name);
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        var username = db.Users.Where(x => x.Id == userid).FirstOrDefault();
        //        string message = $"由" + username.UserName + "提交的" + typename + "需要您的审批,编号为" + number + ",请及时处理!";
        //        LogHelper.LogWarning(DateTime.Now.ToString("yyyy-MM-dd") + "DingDingSendPurchaseMessageMesAsync 钉钉推送消息失败!" + "消息内容为：" + message + "；code:" + code + "；time:" + time + "；jsonstring:" + jsonstring + e.Message);
        //    }
        //}
        ///// <summary>
        ///// 钉钉推送OA消息,用于项目方面的审批通知
        ///// </summary>
        ///// <param name="projectId">项目id</param>
        ///// <param name="userid">发送人id</param>
        ///// <param name="name">项目出库单 / 项目归还单</param>
        ///// <param name="number">审批单编号</param>
        ///// <returns></returns>
        //public static async Task DingDingSendProjectMessageMesAsync(int projectId, int userid, string name, string number)
        //{
        //    try
        //    {
        //        string phone = string.Empty;
        //        int headUserid = Convert.ToInt32(db.Project.Where(y => y.Id == projectId).FirstOrDefault().HeadUserId);
        //        var receiver_user = db.Users.Where(x => x.Id == headUserid).FirstOrDefault();
        //        var username = db.Users.Where(y => y.Id == userid).FirstOrDefault();
        //        string url = onlineurl;
        //        string jsonstring = "{";
        //        var depname = db.Department.Where(x => x.Id == username.DepartmentId).FirstOrDefault().DepartmentName;
        //        var pro = db.Project.Where(x => x.Id == projectId).FirstOrDefault();
        //        jsonstring += "\"申请人\":\"" + depname + " " + username.UserName + "\",";
        //        if (pro != null)
        //        {
        //            jsonstring += "\"项目\":\"" + pro.ProjectName + "\"";
        //        }
        //        jsonstring += "}";
        //        switch (name)
        //        {
        //            case "项目出库单":
        //                url += "AppApproval/ProjectOutboundOrder?number=" + number + "&dd_id=" + receiver_user.DD_number + "";
        //                //url += "AppApproval/ProjectOutboundOrder?number=" + number + "&dd_id=" + UserIdByName(receiver_user) + "";
        //                break;
        //            case "项目归还单":
        //                url += "AppApproval/ProjectReturnOrder?number=" + number + "&dd_id=" + receiver_user.DD_number + "";
        //                //url += "AppApproval/ProjectReturnOrder?number=" + number + "&dd_id=" + UserIdByName(receiver_user) + "";
        //                break;
        //        }
        //        string message = $"由" + username.UserName + "提交的" + name + "需要您的审批,编号为" + number + ",请及时处理!";
        //        if (receiver_user != null)
        //        {
        //            //20221214因为钉钉api接口调用次数限制关闭钉钉消息推送
        //            //await asyncsend_v2(receiver_user.DD_number, message, url, jsonstring);
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        LogHelper.LogWarning(DateTime.Now.ToString("yyyy-MM-dd") + "DingDingSendPurchaseReceiptMessageMesAsync 钉钉推送消息失败!" + e.Message);
        //    }
        //}



        ///// <summary>               
        ///// 通过钉钉ID获取钉钉中对应的每个人的姓名
        ///// </summary>
        ///// <param name="name"></param>
        ///// <returns></returns>
        //public static string UserIdByDD_Id(string userid_dd)
        //{
        //    var namelis = userid_dd.Split(',');
        //    string id = "";
        //    foreach (var item in namelis)
        //    {
        //        foreach (var ite in access.attendances)
        //        {
        //            if (ite.UserNumber == item)
        //            {
        //                id += ite.UserName + ",";
        //            }
        //        }
        //    }
        //    if (id != "")
        //    {
        //        if (id.Substring(id.Length - 1, 1) == "," ? true : false)
        //        {
        //            id = id.Substring(0, id.Length - 1);
        //        }
        //    }

        //    return id;
        //}
        ///// <summary>
        ///// 获取钉钉access_token
        ///// </summary>
        ///// <param name="appkey"></param>
        ///// <param name="appsecret"></param>
        ///// <returns></returns>
        //public async static Task gettoken()
        //{
        //    await Task.Run(() =>
        //    {
        //        string access_token = "";
        //        IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
        //        OapiGettokenRequest req = new OapiGettokenRequest();
        //        req.Appkey = "ding6egsbcyqsluk8awe";
        //        req.Appsecret = "BVfizW17fDB_G9a-xgUsE_m6QrzwY_gqaHy97jsNK9IwTgaJLwFQzoDGyfEeLMOu";
        //        req.SetHttpMethod("GET");
        //        OapiGettokenResponse rsp = client.Execute(req, access_token);
        //        JObject obj = (JObject)JsonConvert.DeserializeObject(rsp.Body);//转换为json对象
        //        access.access_token = obj["access_token"].ToString();
        //        //getuserlis();
        //    });
        //}
        //#endregion

        //#region 根据模块或者资源找出权限码，然后得到电话号码
        ///// <summary>
        ///// 根据资源的权限码获取第一个拥有此权限的用户的电话号码
        ///// </summary>
        ///// <param name="code">资源权限码</param>
        ///// <returns></returns>
        //public static string GetPhoneByCode(string code)
        //{
        //    string phone = string.Empty;
        //    var role = db.Role.Where(x => x.RoleNumber.Contains(code)).FirstOrDefault();
        //    if (role != null)
        //    {
        //        Users user = new Users();
        //        var users = db.Users.Where(y => y.RoleId.Contains(role.Id.ToString()) && y.InternshipState != (int)InternshipStateEnum.Quit);
        //        foreach (var u in users)
        //        {
        //            string[] roleids = u.RoleId.Split(',');
        //            if (roleids.ToList().Contains(role.Id.ToString()))
        //            {
        //                user = u;
        //                break;
        //            }
        //        }
        //        if (user != null)
        //            phone = user.Phone;
        //    }
        //    return phone;
        //}
        ///// <summary>
        ///// 根据资源的权限码获取第一个拥有此权限的用户的Id
        ///// </summary>
        ///// <param name="code">资源权限码</param>
        ///// <returns></returns>
        //public static string GetIdByCode(string code)
        //{
        //    string id = string.Empty;
        //    var role = db.Role.Where(x => x.RoleNumber.Contains(code)).FirstOrDefault();
        //    if (role != null)
        //    {
        //        Users user = new Users();
        //        var users = db.Users.Where(y => y.RoleId.Contains(role.Id.ToString()) && y.InternshipState != (int)InternshipStateEnum.Quit);
        //        foreach (var u in users)
        //        {
        //            string[] roleids = u.RoleId.Split(',');
        //            if (roleids.ToList().Contains(role.Id.ToString()))
        //            {
        //                user = u;
        //                break;
        //            }
        //        }
        //        if (user != null)
        //            id = user.Id.ToString();
        //    }
        //    return id;
        //}
        ///// <summary>
        ///// 根据资源的权限码获取第一个拥有此权限的用户的姓名
        ///// </summary>
        ///// <param name="code">资源权限码</param>
        ///// <returns></returns>
        //public static string GetNameByCode(string code)
        //{
        //    string name = string.Empty;
        //    var role = db.Role.Where(x => x.RoleNumber.Contains(code)).FirstOrDefault();
        //    if (role != null)
        //    {
        //        Users user = new Users();
        //        var users = db.Users.Where(y => y.RoleId.Contains(role.Id.ToString()) && y.InternshipState != (int)InternshipStateEnum.Quit);
        //        foreach (var u in users)
        //        {
        //            string[] roleids = u.RoleId.Split(',');
        //            if (roleids.ToList().Contains(role.Id.ToString()))
        //            {
        //                user = u;
        //                break;
        //            }
        //        }
        //        if (user != null)
        //            name = user.UserName.ToString();
        //    }
        //    return name;
        //}
        //#endregion

        ///*
        ///// <summary>
        ///// 获取添加的工资人的绩效
        ///// </summary>
        ///// <param name="userId">工资人</param>
        ///// <param name="date">日期</param>
        ///// <returns></returns>
        //public Achievements GetAchievementForWages(int userId, DateTime date)
        //{
        //    return db.Achievements.Where(l => l.UserId == userId && l.AchievementDate == date).FirstOrDefault();
        //}
        ///// <summary>
        ///// 获取添加的工资人的考勤
        ///// </summary>
        ///// <param name="userId">工资人</param> 
        ///// <param name="date">日期</param>
        ///// <returns></returns>
        //public Attendance GetAttendanceForWages(int userId, DateTime date)
        //{
        //    return db.Attendance.Where(l => l.UserId == userId && l.AttendanceDate == date).FirstOrDefault();
        //}
        ///// <summary>
        ///// 计算绩效分数
        ///// </summary>
        ///// <param name="self"></param>
        ///// <param name="depart"></param>
        ///// <param name="conpand"></param>
        ///// <returns></returns>
        //public double? CalcAchievementScore(int? self, int? depart, int? conpand)
        //{
        //    var score = 0.4 * self + 0.3 * depart + 0.3 * conpand;
        //    return score;
        //}
        ///// <summary>
        ///// 计算绩效等级和系数
        ///// </summary>
        ///// <param name="score">绩效分数</param>
        ///// <returns>系数,等级</returns>
        //public Tuple<double, string> CalcAchievementlvAndRate(double? score)
        //{
        //    var rate = 0.0;
        //    var Lv = " ";
        //    if (100 >= score && score >= 94)
        //    {
        //        rate = 1.2;
        //        Lv = "A";
        //    }
        //    else if (94 > score && score >= 88)
        //    {
        //        rate = 1;
        //        Lv = "B+";
        //    }
        //    else if (88 > score && score >= 78)
        //    {
        //        rate = 0.8;
        //        Lv = "B";
        //    }
        //    else if (78 >= score && score >= 62)
        //    {
        //        rate = 0.6;
        //        Lv = "C";
        //    }
        //    else if (62 > score && score >= 0)
        //    {
        //        rate = 0.2;
        //        Lv = "D";
        //    }
        //    return new Tuple<double, string>(rate, Lv);
        //}
        ///// <summary>
        ///// 日期取一号  比如 2018.1.25   => 2018.1.1
        ///// </summary>
        ///// <param name="date"></param>
        ///// <returns></returns>
        //public DateTime DateToNo1(DateTime date)
        //{
        //    var year = date.Year;
        //    var mon = date.Month;
        //    return new DateTime(year, mon, 1);
        //}
        ///// <summary>
        ///// 获取报销金额和物品
        ///// </summary>
        ///// <param name="self"></param>
        ///// <param name="depart"></param>
        ///// <param name="conpand"></param>
        ///// <returns></returns>
        //public Tuple<decimal, string, string> GetReimbursementMoneyAndGoodsAndId(int userId, DateTime date)
        //{
        //    var last = date.AddMonths(-1);

        //    var ls = db.Reimbursement.Where(l => l.UserId == userId && last <= l.ReimbursementDate && l.ReimbursementDate < date);
        //    var ReimbursementId = "";
        //    var ReimbursementGoods = "";
        //    var Money = 0.0m;
        //    if (ls.Count() > 0)
        //    {
        //        List<int> arrId = new List<int>();
        //        List<string> arrGoods = new List<string>();
        //        foreach (var t in ls)
        //        {
        //            arrId.Add(t.Id);
        //            arrGoods.Add(t.ReimbursementGoods);
        //            Money += t.ReimbursementAmount;
        //        }
        //        ReimbursementId = string.Join(",", arrId);
        //        ReimbursementGoods = string.Join(",", arrGoods);
        //    }

        //    return new Tuple<decimal, string, string>(Money, ReimbursementGoods, ReimbursementId);
        //}
        ///// <summary>
        ///// 获取请假天数
        ///// </summary>
        ///// <param name="userId"></param>
        ///// <param name="date">工资日期</param>
        ///// <returns></returns>
        //public double GetLeaveDays(int userId, DateTime date)
        //{
        //    var last = date.AddMonths(-1);
        //    var ls = db.Leave.Where(l => l.EmployeesId == userId && last <= l.StartTime && l.EndTime < date);
        //    double n = 0;
        //    if (ls.Count() > 0)
        //    {
        //        foreach (var t in ls)
        //        {
        //            n += t.LeaveDays;
        //        }
        //    }
        //    return n;
        //}
        //#endregion


        //#region  对象转换

        ///// <summary>
        ///// 反射对象赋值该方法只支持属性
        ///// </summary>
        ///// <typeparam name="TIn"></typeparam>
        ///// <typeparam name="TOut"></typeparam>
        ///// <param name="tIn"></param>
        ///// <returns></returns>
        //public static VehicleManagement Trans(VehicleManagement tOut)
        //{
        //    var tIn = db.VehicleManagement.Where(x => x.Id == tOut.Id).FirstOrDefault();
        //    //TOut tOut = Activator.CreateInstance<TOut>();
        //    foreach (var itemOut in tOut.GetType().GetProperties())
        //    {
        //        var propIn = tIn.GetType().GetProperty(itemOut.Name);
        //        if (propIn.GetValue(tIn) == null || propIn.GetValue(tIn).ToString().Length < 1)
        //        {
        //            continue;
        //        }

        //        itemOut.SetValue(tOut, propIn.GetValue(tIn));
        //    }
        //    return tOut;
        //}


        //#endregion


        //#region 物资模块公共类
        ///// <summary>
        ///// 通过采购新增物资
        ///// </summary>
        //public static Device AddDevice(PurchaseGoods good, int userId)
        //{
        //    Device device = new Device();
        //    //device.DeviceNumber = good.DeviceNumber;
        //    //device.DeviceName = good.GoodsName;
        //    //device.DeviceModel = good.ModelType;
        //    device.Price = good.ReviewUnitPrice;
        //    device.State = 1;
        //    //var mo = good.ModelType;
        //    //var na = good.GoodsName;
        //    //var mopinyin = PinYinConverterHelp.GetTotalPinyin(mo);
        //    //var napinyin = PinYinConverterHelp.GetTotalPinyin(na);
        //    //device.Pinyin = mopinyin.FirstPingYin + " " + mopinyin.TotalPingYin + " " + napinyin.FirstPingYin + " " + napinyin.TotalPingYin;
        //    device.PurchaseDate = DateTime.Now;
        //    device.Operator = userId;
        //    //device.Unit = good.Unit;
        //    //device.DeviceCategoryIdOne = good.DeviceCategoryIdOne;
        //    //device.DeviceCategoryIdTwo = good.DeviceCategoryIdTwo;
        //    device.Deleted = false;
        //    return device;
        //}
        ///// <summary>
        ///// 修改物资
        ///// </summary>
        //public static Device UpdateDevice(Device device, Device dev)
        //{
        //    device.Amount = device.Amount + dev.Amount;
        //    device.StockAmount = device.StockAmount + dev.Amount;
        //    device.StockPrice = device.StockPrice + dev.TotalPrice;
        //    device.TotalPrice = device.TotalPrice + dev.TotalPrice;
        //    return device;
        //}
        ///// <summary>
        ///// 把字符串转int数组排序后再转为字符串
        ///// </summary>
        ///// <param name="str">要转换的字符串</param>
        ///// <param name="separator">分隔符(字符串)</param>
        ///// <returns></returns>
        //public string ArraySortToString(string str, string separator)
        //{
        //    string[] sArray = Regex.Split(str, separator, RegexOptions.IgnoreCase);
        //    int[] nArray = Array.ConvertAll<string, int>(sArray, int.Parse);
        //    List<int> lArray = nArray.ToList();
        //    lArray.Sort();//从大到小
        //    var restult = String.Join(",", lArray);
        //    return restult;
        //}
        //#endregion

        //#region 补足位数
        //public static string ComplementDigit(int length, string data)
        //{
        //    string result = string.Empty;
        //    for (int i = 0; i < length - data.Length; i++)
        //    {
        //        result += "0";
        //    }
        //    return result + data;
        //}
        //#endregion

        //#region 短信测试功能
        ///// <summary>
        ///// 发送短信接口，调用发送短信api
        ///// </summary>
        ///// <param name="phone">接受短信电话号码</param>
        ///// <param name="tpl_id">即将使用的短信模板码</param>
        ///// <param name="param">短信模板中即将使用的参数</param>
        //public static async Task SendTestMesAsync(string phone, long tpl_id, string[] param)
        //{
        //    await Task.Run(() =>
        //    {
        //        //post多个参数
        //        string para = null;
        //        if (param != null)
        //        {
        //            for (int i = 0; i < param.Length; i++)
        //            {
        //                para += "&param=" + param[i];
        //            }
        //        }
        //        var content = new StringContent(string.Format("phone={0}&tpl_id={1}{2}", phone, tpl_id, para));
        //        HttpContent httpContent = content;
        //        httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
        //        using (HttpClient httpClient = new HttpClient())
        //        {
        //            string responseJson = httpClient.PostAsync("http://192.168.0.158:96/api/PublicApi/Sendsms", httpContent)
        //              .Result.Content.ReadAsStringAsync().Result;
        //            //string responseJson = httpClient.PostAsync("http://localhost:27047/api/PublicApi/Sendsms", httpContent)
        //            //   .Result.Content.ReadAsStringAsync().Result;
        //            JObject jo = (JObject)JsonConvert.DeserializeObject(responseJson);
        //            var result = jo["result"].ToString();
        //            if (result != "0")
        //            {
        //                LogHelper.WriteLog(DateTime.Now.ToString("yyyy-MM-dd") + "短信发送失败,请联系管理员!");
        //            }
        //            else
        //            {
        //                LogHelper.WriteLog(DateTime.Now.ToString("yyyy-MM-dd") + "短信发送成功!");
        //            }
        //        }
        //    });
        //}
        //#endregion

        //#region 发送短信

        ///// <summary>
        ///// 构造签批通知的短信
        ///// </summary>
        ///// <param name="code">待验证的资源权限码，如果code为null，代表取传入用户部长的电话，为资源码，代表取当前资源码权限所属用户的电话</param>
        ///// <param name="name">待签批的单子类型名称，比如采购单、申购单</param>
        ///// <param name="number">待签批单子编号</param>
        //public static async Task BuildSendDeviceMesAsync(string code, int userid, string name, string number, bool isLeaderShip = false)
        //{
        //    try
        //    {
        //        await Task.Run(() =>
        //        {
        //            string phone = string.Empty;
        //            //如果传过来的资源权限码为空，默认为应该寻找部长的电话号码，通知其审批
        //            if (string.IsNullOrEmpty(code))
        //            {
        //                int DepartmentId = db.Users.Where(y => y.Id == userid).FirstOrDefault().DepartmentId;
        //                if (isLeaderShip)
        //                {
        //                    int LeaderShip = db.Department.Where(x => x.DepartmentId == DepartmentId).FirstOrDefault().LeaderShip;
        //                    phone = db.Users.Where(y => y.Id == LeaderShip).FirstOrDefault().Phone;
        //                }
        //                else
        //                {
        //                    int PartOwner = db.Department.Where(x => x.DepartmentId == DepartmentId).FirstOrDefault().PartOwner;
        //                    phone = db.Users.Where(y => y.Id == PartOwner).FirstOrDefault().Phone;
        //                }
        //            }
        //            else
        //            {
        //                phone = GetPhoneByCode(code);
        //            }
        //            string username = db.Users.Where(y => y.Id == userid).FirstOrDefault().UserName;
        //            string[] Parm = { username, name, number };
        //            if (!string.IsNullOrEmpty(phone))
        //            {
        //                SendMesAsync(phone, tpl_Purchase_id, Parm);
        //            }
        //        });
        //    }
        //    catch (Exception e)
        //    {
        //        LogHelper.WriteLog(DateTime.Now.ToString("yyyy-MM-dd") + "短信消息推送失败!" + e.Message + "");
        //    }
        //}

        ///// <summary>
        ///// 构造项目报表签批通知的短信
        ///// </summary>
        ///// <param name="code">待验证的资源权限码，如果code为null，代表取传入用户部长的电话，为资源码，代表取当前资源码权限所属用户的电话</param>
        ///// <param name="projectId">项目id，根据此信息查找项目名称和编号信息</param>
        ///// <param name="projectReportType">当前审批的项目报表类型</param>
        ///// <param name="userid">如果需要此id的部长进行审批，则需要此信息</param>
        ///// <returns></returns>
        //public static async Task BuildSendProjectMesAsync(int projectId, string projectReportType, string code, int DepartmentId = 0, int HeadUserid = 0)
        //{
        //    try
        //    {
        //        await Task.Run(() =>
        //        {
        //            string phone = string.Empty;
        //            //如果传过来的资源权限码为空，默认为应该寻找部长的电话号码，通知其审批
        //            if (string.IsNullOrEmpty(code))
        //            {
        //                if (DepartmentId != 0)
        //                {
        //                    int PartOwner = db.Department.Where(x => x.DepartmentId == DepartmentId).FirstOrDefault().PartOwner;
        //                    phone = db.Users.Where(y => y.Id == PartOwner).FirstOrDefault().Phone;
        //                }
        //                else if (HeadUserid != 0)
        //                {
        //                    phone = db.Users.Where(y => y.Id == HeadUserid).FirstOrDefault().Phone;
        //                }
        //            }
        //            else
        //            {
        //                phone = GetPhoneByCode(code);
        //            }
        //            Project p = db.Project.Where(x => x.Id == projectId).FirstOrDefault();
        //            string[] Parm = { p.ProjectName, p.ProjectNumber, projectReportType };
        //            if (!string.IsNullOrEmpty(phone))
        //            {
        //                SendMesAsync(phone, tpl_ProjectReport_id, Parm);
        //            }
        //        });
        //    }
        //    catch (Exception e)
        //    {
        //        LogHelper.WriteLog(DateTime.Now.ToString("yyyy-MM-dd") + "项目报表短信消息推送失败!" + e.Message + "");
        //    }
        //}
        ///// <summary>
        ///// 构造项目物资库的签批通知的短信
        ///// </summary>
        ///// <param name="projectId">项目标识，根据项目id取出项目负责人的电话号码</param>
        ///// <param name="name">待签批的单子类型名称，比如采购单、申购单</param>
        ///// <param name="number">待签批单子编号</param>
        //public static async Task BuildSendProjectMaterialMesAsync(int projectId, int userid, string name, string number)
        //{
        //    try
        //    {
        //        await Task.Run(() =>
        //        {
        //            string phone = string.Empty;
        //            string headUserid = db.Project.Where(y => y.Id == projectId).FirstOrDefault().HeadUserId;
        //            phone = db.Users.Where(x => x.Id == Convert.ToInt32(headUserid)).FirstOrDefault().Phone;
        //            string username = db.Users.Where(y => y.Id == userid).FirstOrDefault().UserName;
        //            string[] Parm = { username, name, number };
        //            if (!string.IsNullOrEmpty(phone))
        //            {
        //                SendMesAsync(phone, tpl_Purchase_id, Parm);
        //            }
        //        });
        //    }
        //    catch (Exception e)
        //    {
        //        LogHelper.WriteLog(DateTime.Now.ToString("yyyy-MM-dd") + "项目物资短信消息推送失败!" + e.Message + "");
        //    }
        //}
        //#endregion

        //#region OA消息推送接口
        ///// <summary>
        ///// OA消息推送(516927短信的消息通知)
        ///// </summary>
        ///// <param name="code">待验证的资源权限码，如果code为null，代表取传入用户部长的电话，为资源码，代表取当前资源码权限所属用户的电话</param></param>
        ///// <param name="userid">发送人Id</param>
        ///// <param name="typename">消息类型(申购单\采购单)</param>
        ///// <param name="number">(申购单\采购单)编号</param>
        ///// <returns></returns>
        //public static async Task BuildSendPurchaseMessageMesAsync(string code, int userid, string typename, string number, bool isLeaderShip = false)
        //{
        //    MessageTableController tab = new MessageTableController();
        //    try
        //    {
        //        await Task.Run(() =>
        //        {
        //            string id = string.Empty;
        //            //如果传过来的资源权限码为空，默认为应该寻找部长的电话号码，通知其审批
        //            if (string.IsNullOrEmpty(code))
        //            {
        //                int DepartmentId = db.Users.Where(y => y.Id == userid).FirstOrDefault().DepartmentId;
        //                if (isLeaderShip)
        //                {
        //                    int LeaderShip = db.Department.Where(x => x.DepartmentId == DepartmentId).FirstOrDefault().LeaderShip;
        //                    id = db.Users.Where(y => y.Id == LeaderShip).FirstOrDefault().Id.ToString();
        //                }
        //                else
        //                {
        //                    int PartOwner = db.Department.Where(x => x.DepartmentId == DepartmentId).FirstOrDefault().PartOwner;
        //                    id = db.Users.Where(y => y.Id == PartOwner).FirstOrDefault().Id.ToString();
        //                }
        //            }
        //            else
        //            {
        //                id = GetIdByCode(code);
        //            }
        //            var username = db.Users.Where(x => x.Id == userid).FirstOrDefault().UserName;
        //            if (!string.IsNullOrEmpty(id))
        //            {
        //                string message = $"由" + username + "提交的" + typename + "需要您的审批,编号为" + number + ",请及时处理!";
        //                string url = "";
        //                switch (typename)
        //                {
        //                    case "采购单":
        //                        url = "/Purchase/Index";
        //                        break;
        //                    case "申购单":
        //                        url = "/Purchase/ApplyPurchase";
        //                        break;
        //                    case "入库单":
        //                        url = "/Device/InboundOrder";
        //                        break;
        //                    case "出库单":
        //                        url = "/Device/OutboundOrder";
        //                        break;
        //                    case "归还单":
        //                        url = "/Device/ReturnOrder";
        //                        break;
        //                    case "借款单":
        //                        url = "/Finance/FinanceLoan";
        //                        break;
        //                    case "报销单":
        //                        url = "/Finance/FinanceReimbursement";
        //                        break;
        //                    case "开票申请":
        //                        url = "/Finance/FinanceInvoice";
        //                        break;
        //                }
        //                var res = tab.AddMessage(message, id, "1", url);
        //                //if (!res)
        //                //{
        //                //    LogHelper.WriteLog(DateTime.Now.ToString("yyyy-MM-dd") + "OA消息数据添加失败!");
        //                //}
        //                MessageMesAsync(userid.ToString(), message, id);
        //            }
        //        });
        //    }
        //    catch (Exception e)
        //    {
        //        LogHelper.WriteLog(DateTime.Now.ToString("yyyy-MM-dd") + "；" + e.Message);
        //    }
        //}

        ///// <summary>
        ///// 钉钉推送OA消息,用于项目方面的审批通知
        ///// </summary>
        ///// <param name="projectId">项目id</param>
        ///// <param name="userid">发送人id</param>
        ///// <param name="name">项目出库单 / 项目归还单</param>
        ///// <param name="number">审批单编号</param>
        ///// <returns></returns>
        //public static async Task DingDingSendProjectMessageMesAsync(int projectId, int userid, string name, string number)
        //{
        //    try
        //    {
        //        await Task.Run(() =>
        //        {
        //            string phone = string.Empty;
        //            int headUserid = Convert.ToInt32(db.Project.Where(y => y.Id == projectId).FirstOrDefault().HeadUserId);
        //            var receiver_user = db.Users.Where(x => x.Id == headUserid).FirstOrDefault();
        //            var username = db.Users.Where(y => y.Id == userid).FirstOrDefault();
        //            string url = onlineurl;
        //            string jsonstring = "{";
        //            var depname = db.Department.Where(x => x.DepartmentId == username.DepartmentId).FirstOrDefault().DepartmentName;
        //            var pro = db.Project.Where(x => x.Id == projectId).FirstOrDefault();
        //            jsonstring += "\"申请人\":\"" + depname + " " + username.UserName + "\",";
        //            if (pro != null)
        //            {
        //                jsonstring += "\"项目\":\"" + pro.ProjectName + "\"";
        //            }
        //            jsonstring += "}";
        //            switch (name)
        //            {
        //                case "项目出库单":
        //                    url += "AppApproval/ProjectOutboundOrder?number=" + number + "&dd_id=" + receiver_user.DD_number + "";
        //                    //url += "AppApproval/ProjectOutboundOrder?number=" + number + "&dd_id=" + UserIdByName(receiver_user) + "";
        //                    break;
        //                case "项目归还单":
        //                    url += "AppApproval/ProjectReturnOrder?number=" + number + "&dd_id=" + receiver_user.DD_number + "";
        //                    //url += "AppApproval/ProjectReturnOrder?number=" + number + "&dd_id=" + UserIdByName(receiver_user) + "";
        //                    break;
        //            }
        //            string message = $"由" + username.UserName + "提交的" + name + "需要您的审批,编号为" + number + ",请及时处理!";
        //            if (receiver_user != null)
        //            {
        //                asyncsend_v2(receiver_user.DD_number, message, url, jsonstring);
        //            }
        //        });
        //    }
        //    catch (Exception e)
        //    {
        //        LogHelper.WriteLog(DateTime.Now.ToString("yyyy-MM-dd") + "DingDingSendPurchaseReceiptMessageMesAsync 钉钉推送消息失败!" + e.Message);
        //    }
        //}



        ///// <summary>               
        ///// 通过钉钉ID获取钉钉中对应的每个人的姓名
        ///// </summary>
        ///// <param name="name"></param>
        ///// <returns></returns>
        //public static string UserIdByDD_Id(string userid_dd)
        //{
        //    var namelis = userid_dd.Split(',');
        //    string id = "";
        //    foreach (var item in namelis)
        //    {
        //        foreach (var ite in access.attendances)
        //        {
        //            if (ite.UserNumber == item)
        //            {
        //                id += ite.UserName + ",";
        //            }
        //        }
        //    }
        //    if (id != "")
        //    {
        //        if (id.Substring(id.Length - 1, 1) == "," ? true : false)
        //        {
        //            id = id.Substring(0, id.Length - 1);
        //        }
        //    }

        //    return id;
        //}
        ///// <summary>
        ///// 获取钉钉access_token
        ///// </summary>
        ///// <param name="appkey"></param>
        ///// <param name="appsecret"></param>
        ///// <returns></returns>
        //public async static Task gettoken()
        //{
        //    await Task.Run(() =>
        //    {
        //        string access_token = "";
        //        IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
        //        OapiGettokenRequest req = new OapiGettokenRequest();
        //        req.Appkey = "ding6egsbcyqsluk8awe";
        //        req.Appsecret = "BVfizW17fDB_G9a-xgUsE_m6QrzwY_gqaHy97jsNK9IwTgaJLwFQzoDGyfEeLMOu";
        //        req.SetHttpMethod("GET");
        //        OapiGettokenResponse rsp = client.Execute(req, access_token);
        //        JObject obj = (JObject)JsonConvert.DeserializeObject(rsp.Body);//转换为json对象
        //        access.access_token = obj["access_token"].ToString();
        //        //getuserlis();
        //    });
        //}
        //#endregion

        //#region 发送消息通用接口
        ///// <summary>
        ///// 根据用户id和模块编号，查找相应的审批规则
        ///// </summary>
        ///// <param name="ModuleNumber">模块编号</param>
        ///// <param name="SponsorUserid">数据对应用户id</param>
        ///// <returns></returns>
        //public static AuditRule GetAuditRule(string ModuleNumber, int SponsorUserid)
        //{
        //    AuditRule auditrule = null;
        //    Users user = db.Users.Where(x => x.Id == SponsorUserid).FirstOrDefault();
        //    if (user == null)
        //        return auditrule;
        //    List<AuditRule> auditRules = db.AuditRule.Where(x => !x.Delete && x.ModuleNumber == ModuleNumber).ToList();
        //    foreach (var a in auditRules)
        //    {
        //        if (a.SponsorUser != null && a.SponsorUser.Split(',').Contains(SponsorUserid.ToString()))
        //        {
        //            auditrule = a;
        //            break;
        //        }
        //    }
        //    if (auditrule == null)
        //    {
        //        foreach (var a in auditRules)
        //        {
        //            if (a.SponsorDepart != null && a.SponsorDepart.Split(',').Contains(user.DepartmentId.ToString()))
        //            {
        //                auditrule = a;
        //                break;
        //            }
        //        }
        //    }
        //    return auditrule;
        //}
        //#endregion


        //#region 根据模块或者资源找出权限码，然后得到电话号码
        ///// <summary>
        ///// 根据资源的权限码获取第一个拥有此权限的用户的电话号码
        ///// </summary>
        ///// <param name="code">资源权限码</param>
        ///// <returns></returns>
        //public static string GetPhoneByCode(string code)
        //{
        //    string phone = string.Empty;
        //    var role = db.Role.Where(x => x.RoleNumber.Contains(code)).FirstOrDefault();
        //    if (role != null)
        //    {
        //        Users user = new Users();
        //        var users = db.Users.Where(y => y.RoleId.Contains(role.Id.ToString()) && y.InternshipState != (int)InternshipStateEnum.Quit);
        //        foreach (var u in users)
        //        {
        //            string[] roleids = u.RoleId.Split(',');
        //            if (roleids.ToList().Contains(role.Id.ToString()))
        //            {
        //                user = u;
        //                break;
        //            }
        //        }
        //        if (user != null)
        //            phone = user.Phone;
        //    }
        //    return phone;
        //}
        ///// <summary>
        ///// 根据资源的权限码获取第一个拥有此权限的用户的Id
        ///// </summary>
        ///// <param name="code">资源权限码</param>
        ///// <returns></returns>
        //public static string GetIdByCode(string code)
        //{
        //    string id = string.Empty;
        //    var role = db.Role.Where(x => x.RoleNumber.Contains(code)).FirstOrDefault();
        //    if (role != null)
        //    {
        //        Users user = new Users();
        //        var users = db.Users.Where(y => y.RoleId.Contains(role.Id.ToString()) && y.InternshipState != (int)InternshipStateEnum.Quit);
        //        foreach (var u in users)
        //        {
        //            string[] roleids = u.RoleId.Split(',');
        //            if (roleids.ToList().Contains(role.Id.ToString()))
        //            {
        //                user = u;
        //                break;
        //            }
        //        }
        //        if (user != null)
        //            id = user.Id.ToString();
        //    }
        //    return id;
        //}
        ///// <summary>
        ///// 根据资源的权限码获取第一个拥有此权限的用户的姓名
        ///// </summary>
        ///// <param name="code">资源权限码</param>
        ///// <returns></returns>
        //public static string GetNameByCode(string code)
        //{
        //    string name = string.Empty;
        //    var role = db.Role.Where(x => x.RoleNumber.Contains(code)).FirstOrDefault();
        //    if (role != null)
        //    {
        //        Users user = new Users();
        //        var users = db.Users.Where(y => y.RoleId.Contains(role.Id.ToString()) && y.InternshipState != (int)InternshipStateEnum.Quit);
        //        foreach (var u in users)
        //        {
        //            string[] roleids = u.RoleId.Split(',');
        //            if (roleids.ToList().Contains(role.Id.ToString()))
        //            {
        //                user = u;
        //                break;
        //            }
        //        }
        //        if (user != null)
        //            name = user.UserName.ToString();
        //    }
        //    return name;
        //}
        //#endregion


        //#region 过滤特殊字符
        ///// <summary>
        ///// 过滤特殊字符
        ///// </summary>
        ///// <param name="text"></param>
        ///// <returns></returns>
        //  public static string InputText(string text)
        //   {
        //       text = text.Trim();
        //       if (string.IsNullOrEmpty(text))
        //           return string.Empty;
        //       text = Regex.Replace(text, "[\\s]{2,}", "");    //two or more spaces
        //       text = Regex.Replace(text, "(<[b|B][r|R]/*>)+|(<[p|P](.|\\n)*?>)", "\n");    //<br>
        //       text = Regex.Replace(text, "(\\s*&[n|N][b|B][s|S][p|P];\\s*)+", " ");    //&nbsp;
        //       text = Regex.Replace(text, "<(.|\\n)*?>", string.Empty);    //any other tags
        //       text = text.Replace("'", "");
        //       text = text.Replace("%", "");
        //       text = text.Replace("[", "");
        //       text = text.Replace("]", "");
        //       text = text.Replace("'", "");
        //       text = text.Replace("(", "");
        //       text = text.Replace(")", "");
        //       text = text.Replace("@", "");
        //       text = text.Replace("{", "");
        //       text = text.Replace("}", "");
        //       text = text.Replace("`", "");
        //       text = text.Replace("%", "");
        //       text = text.Replace("!", "");
        //       text = text.Replace("#", "");
        //       text = text.Replace("$", "");
        //       text = text.Replace("%", "");
        //       text = text.Replace("^", "");
        //       text = text.Replace("&", "");
        //       text = text.Replace("*", "");
        //       //text = text.Replace("_", "");
        //       return text;
        //   }

        //#endregion

        //#region 计算财务的总余额
        //public decimal GetFinanceClosingBalance()
        //{
        //    decimal balance = 0;
        //    balance += db.Finance.FirstOrDefault().CashClosingBalance;
        //    balance += db.FinanceBankCard.Where(x => !x.Delete).Sum(y => y.ClosingBalance);
        //    return balance;
        //}
        //#endregion


        //#region 钉钉获取某一天考情数据导入数据库
        ///// <summary>
        ///// 获取打卡数据
        ///// </summary>
        ///// <returns></returns>
        //public bool clockin(string from_date)
        //{
        //    try
        //    {
        //        string data = "";
        //        List<punchclock> clist = new List<punchclock>();
        //        from_date = from_date + " 00:00:00";
        //        //string from_date = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day - 1).ToString("yyyy-MM-dd 00:00:00");               
        //        string to_date = Convert.ToDateTime(from_date).AddDays(1).ToString("yyyy-MM-dd 00:00:00");

        //        var uselis = db.Users.Where(x => x.Deleted == false).ToList();
        //        var list = "";
        //        foreach (var item in uselis)
        //        {
        //            if (item.DD_number != "")
        //            {
        //                list += item.DD_number + ",";
        //                clist.Add(new punchclock(item.DD_number, Convert.ToDateTime(from_date)));
        //            }
        //        }
        //        List<string> lisstring = new List<string>();
        //        var lis = list.Substring(0, list.Length - 1).Split(',').ToList();
        //        int fountcount = (lis.Count / 50) + (lis.Count % 50 == 0 ? 0 : 1);
        //        for (int i = 0; i < fountcount; i++)
        //        {
        //            var newlis = lis.Skip(i * 50).Take(50).ToList();
        //            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/attendance/listRecord");
        //            OapiAttendanceListRecordRequest req = new OapiAttendanceListRecordRequest();
        //            req.UserIds = newlis;
        //            req.CheckDateFrom = from_date;
        //            req.CheckDateTo = to_date;
        //            OapiAttendanceListRecordResponse rsp = client.Execute(req, access.access_token);
        //            JToken objres = (JToken)JsonConvert.DeserializeObject(rsp.Body);
        //            if (objres["errcode"].ToString() == "0")
        //            {
        //                lisstring.Add(objres["recordresult"].ToString());
        //            }
        //        }
        //        if (lisstring.Count < 2)
        //        {
        //            data += lisstring[0];
        //        }
        //        if (lisstring.Count == 2)
        //        {
        //            lisstring[0] = lisstring[0].Substring(0, lisstring[0].Length - 1) + ",";
        //            lisstring[1] = lisstring[1].Substring(1, lisstring[1].Length - 1);
        //            data += lisstring[0] + lisstring[1];
        //        }
        //        if (lisstring.Count > 2)
        //        {
        //            var newjsonstring = "";
        //            for (int i = 0; i < lisstring.Count; i++)
        //            {
        //                if (i == 0)
        //                {
        //                    lisstring[i] = lisstring[i].Substring(lisstring[i].Length - 1, 1) + ",";
        //                }
        //                else if (i == lisstring.Count - 1)
        //                {
        //                    lisstring[i] = lisstring[i].Substring(0, lisstring[i].Length - 1);
        //                }
        //                else
        //                {
        //                    lisstring[i] = lisstring[i].Substring(lisstring[i].Length - 1, 1);
        //                    lisstring[i] = lisstring[i].Substring(0, lisstring[i].Length - 1) + ",";
        //                }
        //                newjsonstring += lisstring[i];
        //            }
        //            data += newjsonstring;
        //        }
        //        JToken @object = (JToken)JsonConvert.DeserializeObject(data);
        //        var clickresult = clockinresult(from_date);//打卡结果数据
        //        foreach (var item in clickresult)
        //        {
        //            if (item.ToString() != "")
        //            {
        //                for (int i = 0; i < clist.Count; i++)
        //                {
        //                    if (clist[i].number_DD == item["userId"].ToString())
        //                    {
        //                        JObject proc = (JObject)item;
        //                        bool procres = proc.Property("procInstId") != null ? true : false;
        //                        if (procres)
        //                        {
        //                            string procInstId = item["procInstId"].ToString();
        //                            JToken proresult = processinstance(procInstId);
        //                            if (proresult["result"].ToString() == "agree")
        //                            {
        //                                string type = proresult["title"].ToString().Substring(proresult["title"].ToString().Length - 2, 2);
        //                                switch (type)
        //                                {
        //                                    case "请假":
        //                                        clist[i].leaved = true;
        //                                        switch (proresult["form_component_values"][0]["value"].ToString())
        //                                        {
        //                                            case "事假":
        //                                                clist[i].leavetype = (int)LeaveEnum.compassionate_leave;
        //                                                break;
        //                                            case "病假":
        //                                                clist[i].leavetype = (int)LeaveEnum.sick_leave;
        //                                                break;
        //                                            case "年假":
        //                                                clist[i].leavetype = (int)LeaveEnum.annual_leave;
        //                                                break;
        //                                            case "婚假":
        //                                                clist[i].leavetype = (int)LeaveEnum.marriage_holiday;
        //                                                break;
        //                                            case "生育假":
        //                                                clist[i].leavetype = (int)LeaveEnum.Maternity_leave;
        //                                                break;
        //                                            case "陪产假":
        //                                                clist[i].leavetype = (int)LeaveEnum.Paternity_leave;
        //                                                break;
        //                                            case "丧假":
        //                                                clist[i].leavetype = (int)LeaveEnum.Bereavement_leave;
        //                                                break;
        //                                            case "工伤假":
        //                                                clist[i].leavetype = (int)LeaveEnum.Industrial_injury_leave;
        //                                                break;
        //                                        }
        //                                        JToken tok = (JToken)JsonConvert.DeserializeObject(proresult["form_component_values"][1]["value"].ToString());
        //                                        clist[i].leave_Starttime = tok[0].ToString();
        //                                        clist[i].leave_Endtime = tok[1].ToString();
        //                                        if (clist[i].leave_Starttime.Split(' ')[0] != clist[i].leave_Endtime.Split(' ')[0])
        //                                        {
        //                                            UpdataLeaved(clist[i]);
        //                                        }
        //                                        break;
        //                                    case "出差":
        //                                        clist[i].businesstravel = proresult["form_component_values"][2]["value"].ToString() + " " + proresult["form_component_values"][1]["name"].ToString() + " " + proresult["form_component_values"][1]["value"].ToString();
        //                                        break;
        //                                }
        //                            }
        //                        }
        //                        //#region 获取打卡的时间数据,部分打卡没有记录但存在结果
        //                        //if (item["timeResult"].ToString() == "NotSigned")
        //                        //{
        //                        //    clist[i].lackOfCards = true;
        //                        //    clist[i].lackOfCardscount += 1;
        //                        //}
        //                        //if (clist[i].lackOfCardscount > 1)
        //                        //{
        //                        //    if (!clist[i].leaved)
        //                        //    {
        //                        //        clist[i].absenteeism = true;
        //                        //        clist[i].lackOfCards = false;
        //                        //    }
        //                        //}
        //                        //#endregion

        //                    }
        //                }
        //                foreach (var ite in @object)
        //                {
        //                    JObject asd = (JObject)item;
        //                    bool zxc = asd.Property("recordId") != null ? true : false;
        //                    if (zxc)
        //                    {
        //                        if (item["recordId"].ToString() == ite["id"].ToString())
        //                        {
        //                            for (int i = 0; i < clist.Count; i++)
        //                            {
        //                                if (clist[i].number_DD == item["userId"].ToString())
        //                                {
        //                                    Apunchclock(ite, clist[i]);
        //                                }
        //                            }
        //                        }
        //                    }
        //                }
        //            }
        //        }
        //        GetApproval(from_date);

        //        businesstravelday(clist, from_date);//处理半天出差的情况问题

        //        delectsame(from_date, to_date);//排除已有的数据

        //        ListToDataTable(clist, "punchclock");
        //        //DataTable dt = SQLBuder.ListToDataTable(clist);
        //        //dt.TableName = "punchclock";
        //        //SQLBuder.InsertByDataTable(dt);
        //        return true;
        //    }
        //    catch (Exception ex)
        //    {
        //        LogHelper.WriteLog($"{DateTime.Now} ×××××××钉钉考情数据获取失败×××××××" + ex.Message);
        //        return false;
        //    }
        //    //数据库批量导入

        //}

        ///// <summary>
        ///// 处理出差(包括半天)的情况问题,外加缺卡和旷工的数据处理
        ///// </summary>
        ///// <param name="clist"></param>
        //public void businesstravelday(List<punchclock> clist, string from_date)
        //{
        //    try
        //    {
        //        foreach (var item in clist)
        //        {
        //            string regex = ".*成都市+.*";
        //            string regex2 = ".*固远晨通+.*";
        //            if ((item.onclickaddress != "" && item.onclickaddress != null) && (item.downclickaddress != "" && item.downclickaddress != null))
        //            {
        //                int morning = (Regex.IsMatch(item.onclickaddress, regex) || Regex.IsMatch(item.onclickaddress, regex2)) == true ? 0 : 1;
        //                int afternoon = (Regex.IsMatch(item.downclickaddress, regex) || Regex.IsMatch(item.downclickaddress, regex2)) == true ? 0 : 1;

        //                switch (morning + afternoon)
        //                {
        //                    case 1:
        //                        item.businesstravelday = "0.5";
        //                        break;
        //                    case 2:
        //                        item.businesstravelday = "1";
        //                        break;
        //                }
        //            }


        //            int card_morning = item.onclicktime == null ? 1 : 0;
        //            int card_afternoon = item.downclicktime == null ? 1 : 0;
        //            switch (card_morning + card_afternoon)
        //            {
        //                case 1:
        //                    item.lackOfCards = true;
        //                    item.lackOfCardscount = 1;
        //                    break;
        //                case 2:
        //                    item.absenteeism = true;
        //                    break;
        //            }
        //            if (item.leaved)
        //            {
        //                List<string> numlis = new List<string>();
        //                numlis.Add(item.number_DD);
        //                IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/attendance/list");
        //                OapiAttendanceListRequest req = new OapiAttendanceListRequest();
        //                req.WorkDateFrom = from_date;
        //                req.WorkDateTo = from_date;
        //                req.UserIdList = numlis;
        //                req.Offset = 0;
        //                req.Limit = 10;
        //                OapiAttendanceListResponse rsp = client.Execute(req, access.access_token);
        //                JToken objres = (JToken)JsonConvert.DeserializeObject(rsp.Body);
        //                var data = (JToken)JsonConvert.DeserializeObject(objres["recordresult"].ToString());

        //                int procres = 0;
        //                for (int i = 0; i < data.Count(); i++)
        //                {
        //                    JObject proc = (JObject)data[i];
        //                    if (proc.Property("procInstId") != null ? true : false)
        //                    {
        //                        procres++;
        //                    }
        //                }
        //                if (procres == 1)
        //                {
        //                    item.leavedday = "0.5";
        //                }
        //                if (procres == 2)
        //                {
        //                    item.lackOfCards = false;
        //                    item.lackOfCardscount = 0;
        //                    item.absenteeism = false;
        //                    item.leavedday = "1";
        //                }
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {

        //        throw;
        //    }

        //}
        ///// <summary>
        ///// 获取打卡结果数据
        ///// </summary>
        ///// <returns></returns>
        //public JToken clockinresult(string from_date)
        //{
        //    string data = "";
        //    var list = "";
        //    var uselis = db.Users.Where(x => x.Deleted == false).ToList();
        //    foreach (var item in uselis)
        //    {
        //        list += item.DD_number + ",";
        //    }
        //    List<string> lisstring = new List<string>();
        //    var lis = list.Substring(0, list.Length - 1).Split(',').ToList();
        //    int fountcount = (lis.Count / 50) + (lis.Count % 50 == 0 ? 0 : 1);
        //    for (int i = 0; i < fountcount; i++)
        //    {
        //        var newlis = lis.Skip(i * 50).Take(50).ToList();
        //        for (int k = 0; k < 2; k++)
        //        {

        //            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/attendance/list");
        //            OapiAttendanceListRequest req = new OapiAttendanceListRequest();
        //            req.WorkDateFrom = from_date;
        //            req.WorkDateTo = from_date;
        //            req.UserIdList = newlis;
        //            req.Offset = k * 50 + k;
        //            req.Limit = 50;
        //            OapiAttendanceListResponse rsp = client.Execute(req, access.access_token);
        //            JToken objres = (JToken)JsonConvert.DeserializeObject(rsp.Body);
        //            if (objres["errcode"].ToString() == "0")
        //            {
        //                lisstring.Add(objres["recordresult"].ToString());
        //            }
        //        }
        //    }
        //    if (lisstring.Count < 2)
        //    {
        //        data += lisstring[0];
        //    }
        //    if (lisstring.Count == 2)
        //    {
        //        lisstring[0] = lisstring[0].Substring(0, lisstring[0].Length - 1) + ",";
        //        lisstring[1] = lisstring[1].Substring(1, lisstring[1].Length - 1);
        //        data += lisstring[0] + lisstring[1];
        //    }
        //    if (lisstring.Count > 2)
        //    {
        //        var newjsonstring = "";
        //        for (int i = 0; i < lisstring.Count; i++)
        //        {
        //            if (i == 0)
        //            {
        //                lisstring[i] = lisstring[i].Substring(0, lisstring[i].Length - 1) + ",";
        //            }
        //            else if (i == lisstring.Count - 1)
        //            {
        //                lisstring[i] = lisstring[i].Substring(1, lisstring[i].Length - 1);
        //            }
        //            else
        //            {
        //                lisstring[i] = lisstring[i].Substring(1, lisstring[i].Length - 1);
        //                lisstring[i] = lisstring[i].Substring(0, lisstring[i].Length - 1) + ",";
        //            }
        //            newjsonstring += lisstring[i];
        //        }
        //        data += newjsonstring;
        //    }
        //    JToken @object = (JToken)JsonConvert.DeserializeObject(data);
        //    object objdata = JsonConvert.DeserializeObject(data);
        //    return @object;
        //}
        ///// <summary>
        ///// 获取加班审批
        ///// </summary>
        ///// <param name="userlis"></param>
        ///// <param name="from_date"></param>
        ///// <returns></returns>
        //public async void GetApproval(string from_date)
        //{

        //    bool result = false;
        //    List<Addworked> lisw = new List<Addworked>();
        //    string jiajiari = await IsHolidayByDate(from_date);
        //    DateTime time = Convert.ToDateTime(from_date);
        //    DateTime timeend = time.AddDays(1);
        //    long start = (time.ToUniversalTime().Ticks - 621355968000000000) / 10000;
        //    long end = (timeend.ToUniversalTime().Ticks - 621355968000000000) / 10000;
        //    IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/listids");
        //    OapiProcessinstanceListidsRequest req = new OapiProcessinstanceListidsRequest();
        //    req.ProcessCode = "PROC-FF6YHERSO2-ONWB4T0HR7AYB1ETQ88K2-NGHIH4QI-BA";//加班
        //    req.StartTime = start;
        //    req.EndTime = end;
        //    OapiProcessinstanceListidsResponse rsp = client.Execute(req, access.access_token);
        //    JToken obj = (JToken)JsonConvert.DeserializeObject(rsp.Body);
        //    result = obj["errcode"].ToString() == "0" ? true : false;
        //    if (obj["result"]["list"].ToString() != "" && obj["result"]["list"].ToString() != null)
        //    {
        //        foreach (var item in obj["result"]["list"])
        //        {
        //            JToken tok = processinstance(item.ToString());

        //            if (tok["status"].ToString() == "COMPLETED")
        //            {
        //                string timed = tok["form_component_values"][0]["value"].ToString().Replace('"', ' ');
        //                timed = timed.Substring(0, timed.Length - 1);
        //                timed = timed.Substring(1, timed.Length - 1);

        //                DateTime t1 = Convert.ToDateTime(timed.Split(',')[0].ToString().Trim());
        //                DateTime t2 = Convert.ToDateTime(timed.Split(',')[1].ToString().Trim());
        //                #region 判断提交的加班在不在同一天的情况               
        //                if (t1.Date != t2.Date)
        //                {
        //                    TimeSpan daydate = t2.Date - t1.Date;
        //                    for (int i = 0; i <= daydate.Days; i++)
        //                    {
        //                        DateTime addwotkdate = t1.AddDays(i);

        //                        var olddata = db.addworked.Where(x => x.todaytime == addwotkdate.Date).ToList();
        //                        foreach (var workold in olddata)
        //                        {
        //                            db.addworked.Remove(workold);
        //                            db.SaveChanges();
        //                        }

        //                        Addworked work2 = new Addworked();
        //                        work2.addwork = true;
        //                        work2.number_DD = tok["originator_userid"].ToString();
        //                        work2.addworktype = await IsHolidayByDate(addwotkdate.ToString("yyyy-MM-dd mm:dd:ss"));
        //                        if (i == 0)
        //                        {
        //                            if (t1.Hour > 12)
        //                            {
        //                                work2.addwork_Starttime = addwotkdate.ToString("yyyy-MM-dd 13:30:00");
        //                                work2.addwork_Endtime = addwotkdate.ToString("yyyy-MM-dd 17:30:00");
        //                                work2.addworktime = "4";
        //                            }
        //                            else
        //                            {
        //                                work2.addwork_Starttime = addwotkdate.ToString("yyyy-MM-dd mm:dd:ss");
        //                                work2.addwork_Endtime = addwotkdate.ToString("yyyy-MM-dd 17:30:00");
        //                                work2.addworktime = "8";
        //                            }
        //                        }
        //                        if (i == daydate.Days)
        //                        {
        //                            if (t2.Hour > 13)
        //                            {
        //                                work2.addwork_Endtime = addwotkdate.ToString("yyyy-MM-dd 17:30:00");
        //                                work2.addworktime = "8";
        //                            }
        //                            else
        //                            {
        //                                work2.addwork_Endtime = t2.ToString("yyyy-MM-dd mm:dd:ss");
        //                                work2.addworktime = "4";
        //                            }
        //                        }
        //                        work2.addwork_Starttime = addwotkdate.ToString("yyyy-MM-dd 08:30:00");
        //                        work2.addwork_Endtime = addwotkdate.ToString("yyyy-MM-dd 17:30:00");
        //                        work2.addworktime = "8";
        //                        work2.todaytime = addwotkdate.Date;
        //                        lisw.Add(work2);
        //                    }
        //                }
        //                #endregion
        //                else
        //                {
        //                    var olddata = db.addworked.Where(x => x.todaytime == t1.Date).ToList();
        //                    foreach (var workold in olddata)
        //                    {
        //                        db.addworked.Remove(workold);
        //                        db.SaveChanges();
        //                    }

        //                    Addworked work = new Addworked();
        //                    var a = timed.Split(',')[0].Trim().Split(' ')[0];
        //                    var b = from_date.Split(' ')[0];
        //                    if (a == b)
        //                    {
        //                        work.addworktype = jiajiari;
        //                    }
        //                    else
        //                    {
        //                        work.addworktype = await IsHolidayByDate(a);
        //                    }
        //                    work.addwork_Starttime = timed.Split(',')[0].ToString().Trim();
        //                    work.addwork_Endtime = timed.Split(',')[1].ToString().Trim();

        //                    work.number_DD = tok["originator_userid"].ToString();
        //                    work.addworktime = tok["form_component_values"][1]["value"].ToString();

        //                    work.todaytime = t1.Date;
        //                    work.addwork = true;

        //                    lisw.Add(work);
        //                }
        //            }
        //        }
        //    }
        //    if (lisw.Count > 0)
        //    {
        //        ListToDataTable(lisw, "addworked");
        //    }
        //}
        ///// <summary>
        ///// 获取审批单数据
        ///// </summary>
        ///// <param name="processInstanceId"></param>
        ///// <returns></returns>
        //public JToken processinstance(string processInstanceId)
        //{
        //    bool result = false;
        //    IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/get");
        //    OapiProcessinstanceGetRequest req = new OapiProcessinstanceGetRequest();
        //    req.ProcessInstanceId = processInstanceId;
        //    OapiProcessinstanceGetResponse rsp = client.Execute(req, access.access_token);
        //    JToken objres = (JToken)JsonConvert.DeserializeObject(rsp.Body);
        //    result = objres["errcode"].ToString() == "0" ? true : false;
        //    return objres["process_instance"];
        //}
        ///// <summary>
        ///// 通过打卡记录获取位置和迟到早退的数据处理
        ///// </summary>
        ///// <param name="ite"></param>
        ///// <param name="pun"></param>
        //public void Apunchclock(JToken ite, punchclock pun)
        //{
        //    string regex = ".*成都市+.*";
        //    if (ite["checkType"].ToString() == "OnDuty")
        //    {
        //        if (((JObject)ite).Property("userAddress") != null)
        //        {
        //            pun.onclickaddress = ite["userAddress"].ToString();
        //            if (Regex.IsMatch(pun.onclickaddress, regex) && ite["locationResult"].ToString() == "Normal")//打卡位置包含成都市或者在规定范围内将取消出差的状体
        //            {
        //                pun.businesstravel = "";
        //            }
        //        }
        //        pun.onclicktime = ConvertLongToDateTime(ite["userCheckTime"].ToString());
        //    }
        //    if (ite["checkType"].ToString() == "OffDuty")
        //    {
        //        if (((JObject)ite).Property("userAddress") != null)
        //        {
        //            pun.downclickaddress = ite["userAddress"].ToString();
        //            if (Regex.IsMatch(pun.downclickaddress, regex) && ite["locationResult"].ToString() == "Normal")//打卡位置包含成都市或者在规定范围内将取消出差的状体
        //            {
        //                pun.businesstravel = "";
        //            }
        //        }
        //        pun.downclicktime = ConvertLongToDateTime(ite["userCheckTime"].ToString());
        //    }
        //    if (pun.businesstravel == "" || pun.businesstravel == null)
        //    {
        //        switch (ite["timeResult"].ToString())
        //        {
        //            case "Early":
        //                pun.leaveearly = true;
        //                pun.leaveearlytime = (Convert.ToDecimal(ite["baseCheckTime"]) - Convert.ToDecimal(ite["userCheckTime"])).ToString();
        //                break;
        //            case "Late":
        //                pun.late = true;
        //                pun.latetime = (Convert.ToDecimal(ite["userCheckTime"]) - Convert.ToDecimal(ite["baseCheckTime"])).ToString();
        //                break;
        //        }
        //    }
        //}



        //public static void delectsame(string time1, string time2)
        //{
        //    using (MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["OAContext"].ConnectionString))
        //    {
        //        string sql = "DELETE FROM `punchclock` WHERE `punchclock`.`todaytime`>='" + time1 + "' AND `punchclock`.`todaytime`<='" + time2 + "'";
        //        conn.Open();
        //        MySqlCommand comm = new MySqlCommand(sql, conn);
        //        comm.ExecuteNonQuery();
        //        conn.Close();
        //    }
        //}

        //#endregion

        //#region 判断登录人员是否是某部门成员,或者是否是高管部门的成员，从而判断是否有操作权限
        ///// <summary>
        ///// 判断是否是部门成员,或者是否是高管部门的成员，从而判断是否有操作权限
        ///// </summary>
        ///// <param name="userId"></param>
        ///// <param name="ProjectId"></param>
        ///// <returns></returns>
        //public bool IsDepartMember(int DepartId, int userId = 0)
        //{
        //    bool isMember = false;
        //    if (userId == 0)
        //        userId = Public.GetUserId();
        //    Users user = db.Users.Find(userId);
        //    if (user != null && (user.DepartmentId == DepartId || user.DepartmentId == Convert.ToInt32(AuditRightDepartEnum.SeniorManage)))
        //        isMember = true;
        //    return isMember;
        //}*/
        //#endregion


        /// <summary>
        /// OA消息推送(516927短信的消息通知)
        /// </summary>
        /// <param name="code">根据新的审批规则构造新的OA消息发送接口
        /// </param></param>
        /// <param name="userid">发送人Id</param>
        /// <param name="typename">消息类型(申购单\采购单)</param>
        /// <param name="number">(申购单\采购单)编号</param>
        /// <returns></returns>
        public static async Task BuildSendAuditMessageMesAsync(int userid, string username, string name, string number, DBContext con)
        {
            MessageTableController tab = new MessageTableController(con);
            try
            {
                await Task.Run(() =>
                {
                    string id = userid.ToString();
                    if (!string.IsNullOrEmpty(id))
                    {
                        string message = $"由" + username + "提交的" + name + "需要您的审批,编号为" + number + ",请及时处理!";
                        string url = "";
                        switch (name)
                        {
                            case "采购单":
                                url = "/Purchase/Index";
                                break;
                            case "申购单":
                                url = "/Purchase/ApplyPurchase";
                                break;
                            case "入库单":
                                url = "/Device/InboundOrder";
                                break;
                            case "出库单":
                                url = "/Device/OutboundOrder";
                                break;
                            case "归还单":
                                url = "/Device/ReturnOrder";
                                break;
                            case "借款单":
                                url = "/Finance/FinanceLoan";
                                break;
                            case "报销单":
                                url = "/Finance/FinanceReimbursement";
                                break;
                            case "开票申请":
                                url = "/Finance/FinanceInvoice";
                                break;
                        }
                        var res = AddMessage(message, id, "1", url);
                        MessageMesAsync(userid.ToString(), message, id);
                    }
                });
            }
            catch (Exception e)
            {
            }
        }

        #region OA消息推送接口
        /// <summary>
        /// OA消息推送(518648短信的消息通知)
        /// </summary>
        /// <param name="code">待验证的资源权限码，如果code为null，代表取传入用户部长的电话，为资源码，代表取当前资源码权限所属用户的电话</param></param>
        /// <param name="id">接收人Id</param>
        /// <param name="typename">消息类型(申购单\采购单)</param>
        /// <param name="number">(申购单\采购单)编号</param>
        /// <returns></returns>
        public static async Task BuildSendRefuseReceiptMessageMesAsync(string id, string typename, string number, string comment)
        {
            MessageTableController tab = new MessageTableController(db);
            try
            {
                string message = $"你提交的编号为" + number + "的" + typename + "已被拒绝，拒绝原因为：" + comment;
                string url = "";
                switch (typename)
                {
                    case "采购单":
                        url = "/Purchase/Index";
                        break;
                    case "申购单":
                        url = "/Purchase/ApplyPurchase";
                        break;
                    case "入库单":
                        url = "/Device/InboundOrder";
                        break;
                    case "出库单":
                        url = "/Device/OutboundOrder";
                        break;
                    case "归还单":
                        url = "/Device/ReturnOrder";
                        break;
                    case "借款单":
                        url = "/Finance/FinanceLoan";
                        break;
                    case "报销单":
                        url = "/Finance/FinanceReimbursement";
                        break;
                    case "开票申请":
                        url = "/Finance/FinanceInvoice";
                        break;
                }
                var res = AddMessage(message, id, "1", url);
                await MessageMesAsync(null, message, id);
            }
            catch (Exception e)
            {
                LogHelper.LogWarning(DateTime.Now.ToString("yyyy-MM-dd") + "；" + e.Message);
            }
        }
        /// <summary>
        /// OA消息推送
        /// </summary>
        /// <param name="userid">发送人Id</param>
        /// <param name="message">消息内容</param>
        /// <param name="receiver">接收人Id</param>
        /// <returns></returns>
        public static async Task MessageMesAsync(string userid, string message, string receiver)
        {
            await Task.Run(() =>
            {
                var content = new StringContent(string.Format($"userid={userid}&message={message}&receiver={receiver}"));
                HttpContent httpContent = content;
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                using (HttpClient httpClient = new HttpClient())
                {
                    string responseJson = httpClient.PostAsync("http://192.168.0.127:96/api/PublicApi/Message", httpContent)
                      .Result.Content.ReadAsStringAsync().Result;
                    //string responseJson = httpClient.PostAsync("http://192.168.0.140:12312/api/PublicApi/Message", httpContent)
                    //   .Result.Content.ReadAsStringAsync().Result;
                    LogHelper.LogWarning(DateTime.Now.ToString("yyyy-MM-dd") + "OA消息推送成功!" + "消息内容：" + message);
                }
            });
        }
        /// <summary>
        /// OA消息推送(518648短信的消息通知)
        /// </summary>
        /// <param name="code">待验证的资源权限码，如果code为null，代表取传入用户部长的电话，为资源码，代表取当前资源码权限所属用户的电话</param></param>
        /// <param name="id">接收人Id</param>
        /// <param name="typename">消息类型(申购单\采购单)</param>
        /// <param name="number">(申购单\采购单)编号</param>
        /// <returns></returns>
        public static async Task BuildSendPurchaseReceiptMessageMesAsync(string id, string typename, string number)
        {
            MessageTableController tab = new MessageTableController(db);
            try
            {
                string message = $"你提交的编号为" + number + "的" + typename + "已审批通过!";
                string url = "";
                switch (typename)
                {
                    case "采购单":
                        url = "/Purchase/Index";
                        break;
                    case "申购单":
                        url = "/Purchase/ApplyPurchase";
                        break;
                    case "入库单":
                        url = "/Device/InboundOrder";
                        break;
                    case "出库单":
                        url = "/Device/OutboundOrder";
                        break;
                    case "归还单":
                        url = "/Device/ReturnOrder";
                        break;
                    case "借款单":
                        url = "/Finance/FinanceLoan";
                        break;
                    case "报销单":
                        url = "/Finance/FinanceReimbursement";
                        break;
                    case "开票申请":
                        url = "/Finance/FinanceInvoice";
                        break;
                }
                var res = AddMessage(message, id, "1", url);
                await MessageMesAsync(null, message, id);
            }
            catch (Exception e)
            {
                LogHelper.LogWarning(DateTime.Now.ToString("yyyy-MM-dd") + "；" + e.Message);
            }
        }
        #endregion

        #region 发送短信
        /// <summary>
        /// 发送短信接口，调用发送短信api
        /// </summary>
        /// <param name="phone">接受短信电话号码</param>
        /// <param name="tpl_id">即将使用的短信模板码</param>
        /// <param name="param">短信模板中即将使用的参数</param>
        public static async Task SendMesAsync(string phone, long tpl_id, string[] param)
        {
            try
            {
                await Task.Run(() =>
                {
                    //post多个参数
                    string para = null;
                    if (param != null)
                    {
                        for (int i = 0; i < param.Length; i++)
                        {
                            para += "&param=" + param[i];
                        }
                    }
                    var content = new StringContent(string.Format("phone={0}&tpl_id={1}{2}", phone, tpl_id, para));
                    HttpContent httpContent = content;
                    httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                    using (HttpClient httpClient = new HttpClient())
                    {
                        string responseJson = httpClient.PostAsync("http://192.168.0.127:96/api/PublicApi/Sendsms", httpContent)
                          .Result.Content.ReadAsStringAsync().Result;
                        //string responseJson = httpClient.PostAsync("http://localhost:27047/api/PublicApi/Sendsms", httpContent)
                        //   .Result.Content.ReadAsStringAsync().Result;
                        JObject jo = (JObject)JsonConvert.DeserializeObject(responseJson);
                        if (jo != null)
                        {
                            var result = jo["result"].ToString();
                            if (result != "0")
                            {
                                LogHelper.LogWarning(DateTime.Now.ToString("yyyy-MM-dd") + "短信发送失败,请联系管理员!");
                            }
                            else
                            {
                                LogHelper.LogWarning(DateTime.Now.ToString("yyyy-MM-dd") + "短信发送成功!");
                            }
                        }
                        else
                        {
                            LogHelper.LogWarning("短信api返回的内容为空，" + DateTime.Now.ToString("yyyy-MM-dd") + "短信发送失败,请联系管理员!");
                        }
                    }
                });
            }
            catch (Exception e)
            {
                LogHelper.LogWarning("短信发送出现异常，异常内容：" + e.Message);
            }
        }
        /// <summary>
        /// 发送审批被拒绝的短信
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="name"></param>
        /// <param name="number"></param>
        /// <returns></returns>
        public static async Task BuildSendRefuseReceiptAsync(int userid, string name, string number, string comment)
        {
            try
            {
                string phone = db.Users.Where(y => y.Id == userid).FirstOrDefault().Phone;
                string[] Parm = { number, name, comment };
                if (!string.IsNullOrEmpty(phone))
                {
                    await SendMesAsync(phone, tpl_AuditRefuse_id, Parm);
                }
            }
            catch (Exception e)
            {
                LogHelper.LogWarning(DateTime.Now.ToString("yyyy-MM-dd") + "短信拒绝回执推送失败!" + e.Message + "");
            }
        }
        /// <summary>
        /// 根据新的审批规则，给下一级发送审批短信
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="name"></param>
        /// <param name="number"></param>
        /// <returns></returns>
        public static async Task BuildSendAuditMesAsync(int userid, string username, string name, string number)
        {
            try
            {
                string phone = db.Users.Where(y => y.Id == userid).FirstOrDefault().Phone;
                string[] Parm = { username, name, number };
                if (!string.IsNullOrEmpty(phone))
                {
                    await SendMesAsync(phone, tpl_Purchase_id, Parm);
                }
            }
            catch (Exception e)
            {
                LogHelper.LogWarning(DateTime.Now.ToString("yyyy-MM-dd") + "短信推送失败!" + e.Message + "");
            }
        }
        /// <summary>
        /// 采购与物资的单据审核通过后给申请人发送回执
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="name"></param>
        /// <param name="number"></param>
        /// <returns></returns>
        public static async Task BuildSendDeviceMesReceiptAsync(int userid, string name, string number)
        {
            try
            {
                string phone = db.Users.Where(y => y.Id == userid).FirstOrDefault().Phone;
                string[] Parm = { number, name };
                if (!string.IsNullOrEmpty(phone))
                {
                    await SendMesAsync(phone, tpl_PurchaseReceipt_id, Parm);
                }
            }
            catch (Exception e)
            {
                LogHelper.LogWarning(DateTime.Now.ToString("yyyy-MM-dd") + "短信回执推送失败!" + e.Message + "");
            }
        }
        #endregion


        #region 验证当前用户是否有操作权限和验证是否有部长权限
        /// <summary>
        /// 验证当前用户是否有操作权限
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static bool ValidateRightUser(int id, int userId)
        {
            return userId == id ? true : false;
        }
        /// <summary>
        /// 验证当前用户是否有部长操作权限
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static bool ValidateRightProjectHeadUser(int ProjectId, int userId)
        {
            Project p = db.Project.Where(x => x.Id == ProjectId).FirstOrDefault();
            return userId == Convert.ToInt32(p.HeadUserId) ? true : false;
        }
        #endregion

        #region 根据Enum类型返回 json 字典<值,Description>  
        /// <summary>
        /// 枚举转换值与Description保存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        //public static string GetEnumDESDictionaryToJson<T>() where T : Enum
        //{
        //    Dictionary<int, string> enumDic = new Dictionary<int, string>();
        //    Type t = typeof(T);
        //    Array arrays = Enum.GetValues(t);
        //    for (int i = 0; i < arrays.LongLength; i++)
        //    {
        //        var test = arrays.GetValue(i);
        //        FieldInfo fieldInfo = test.GetType().GetField(test.ToString());
        //        object[] attribArray = fieldInfo.GetCustomAttributes(false);

        //        var name = test.ToString();
        //        var field = test.GetType().GetField(name);
        //        if (field == null) return name;
        //        var att = System.Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute), false);
        //        var namevalue = (att == null ? field.Name : ((DescriptionAttribute)att).Description);
        //        enumDic.Add((int)test, namevalue);
        //    }
        //    return JsonConvert.SerializeObject(enumDic);
        //}

        ////枚举转换值与Description保存
        public static List<EnumType> GetEnumDESVal<T>() where T : Enum
        {
            List<EnumType> enumTypes = new List<EnumType>();
            Type t = typeof(T);
            Array arrays = Enum.GetValues(t);
            for (int i = 0; i < arrays.LongLength; i++)
            {
                EnumType enumType = new EnumType();
                var test = arrays.GetValue(i);
                var name = test.ToString();
                var field = test.GetType().GetField(name);
                var att = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute), false);
                enumType.value = (int)test;
                enumType.name = att == null ? "" : ((DescriptionAttribute)att).Description;
                enumTypes.Add(enumType);
            }
            return enumTypes;
        }
        #endregion

        #region 获取目标路径下所有的文件信息
        public List<string> GetUrlDocument(string url)
        {
            //文件地址路径
            List<string> urllist = new List<string>();
            //虚拟地址路径
            List<string> NewurlPath = new List<string>();
            List<string> namepath = new List<string>();
            //获取文件路径
            try
            {
                var path = AppDomain.CurrentDomain.BaseDirectory;
                var root = Path.GetPathRoot(path);
                urllist.Add(root);
                urllist.Add(PublicMethodApiController.FileloadStr);
                urllist.Add("1");
                //拼接虚拟显示路径~
                NewurlPath.Add("/" + PublicTool.OAFile);

                for (int i = 0; i < url.Split(',').Count(); i++)
                {
                    urllist.Add(url.Split(',')[i]);
                    NewurlPath.Add(url.Split(',')[i]);
                }
                string newPath = Path.Combine(urllist.ToArray()); // newPath = "D:\temp\result.txt";
                if (Directory.Exists(newPath))
                {
                    DirectoryInfo di = new DirectoryInfo(newPath);
                    FileInfo[] fis = di.GetFiles();
                    //正式环境下的虚拟路径拼接，测试环境注释即可
                    string newpath = Path.Combine(NewurlPath.ToArray());
                    foreach (FileInfo fi in fis)
                    {
                        string name = fi.Name;
                        var funamelst = name.LastIndexOf('.') + 1;
                        var newname = name.Substring(funamelst).ToUpper();
                        if (newname == "PNG" || newname == "JPG" || newname == "JPEG")
                        {
                            namepath.Add(Path.Combine(newpath, name));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                LogHelper.LogWarning(DateTime.Now.ToString("yyyy-MM-dd") + "获取文件路径失败!" + e.Message + "");
            };
            return namepath;
        }
        #endregion

        #region 保存文件、删除文件、获取文件信息
        public static bool SaveFile(string path, IFormFile file, string newname)
        {
            try
            {
                //保存上传的文件
                if (!Directory.Exists(path))  //判断路径是否存在 不存在创建
                {
                    DirectoryInfo dirinfo = Directory.CreateDirectory(path);
                    dirinfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;
                }
                var filePath = Path.Combine(path, newname);
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    file.CopyTo(stream);
                }
                ////var fileName = file.FileName; //获取文件名
                //using (var fs = System.IO.File.Create(path + @"\" + newname))
                //{
                //    file.CopyTo(fs);
                //    fs.Flush();
                //    fs.Close();
                //}
                return true;
            }
            catch (Exception ex)
            {

                return false;
            }
        }

        /// <summary>
        /// 删除指定路径下文件或者目录
        /// </summary>
        /// <param name="Path"></param>
        /// <param name="IsDelDirectory">是否是根目录</param>
        /// <returns></returns>
        public static bool DeleteFile(string Path, bool IsDelDirectory)
        {
            bool result = true;
            //删除文件夹
            if (Directory.Exists(Path))  //判断路径是否存在 
            {
                try
                {
                    DirectoryInfo dirinfo = new DirectoryInfo(Path);
                    if (IsDelDirectory)
                    {
                        //Directory.Delete(Path,true);
                        dirinfo.Delete(true);
                    }
                    else
                    {
                        FileInfo[] files = dirinfo.GetFiles(); // 获取该目录下的所有文件
                        foreach (FileInfo file in files)
                        {
                            file.Delete();
                        }
                    }

                }
                catch
                {
                    result = false;
                }
            }
            //删除文件
            if (File.Exists(Path))
            {
                FileInfo fileInfo = new FileInfo(Path);
                fileInfo.Delete();
            }
            return result;
        }

        /// <summary>
        /// 获取指定路径下文件信息
        /// </summary>
        /// <param name="Path"></param>
        /// <returns></returns>
        public static List<Files> GetFileInfo(string type, string FilePath,string DelFileName="")
        {
            List<Files> listFiles = new List<Files>();
            var path = AppDomain.CurrentDomain.BaseDirectory;
            var root = Path.GetPathRoot(path);
            string serverPath = root + PublicMethodApiController.FileloadStr + "\\" + "1\\" + FilePath;//1代表OA系统
            if (Directory.Exists(serverPath))  //判断路径是否存在 
            {
                try
                {
                    DirectoryInfo dirinfo = new DirectoryInfo(serverPath);
                    FileInfo[] files = dirinfo.GetFiles(); //获取该目录下的所有文件
                    foreach (FileInfo file in files)
                    {
                        Files filesInfo = new Files();
                        filesInfo.Type = type;
                        filesInfo.FileName = file.Name;
                        filesInfo.Size = ((double)file.Length / (1024 * 1024)).ToString("0.00") + "MB";
                        filesInfo.Date = file.CreationTime;
                        filesInfo.Url = OAFile + "\\" + FilePath + "\\" + file.Name;
                        listFiles.Add(filesInfo);
                    }
                }
                catch
                {

                }
            }
            return listFiles;
        }


        public static string GetPaht(int FileType, int id, int Type, bool Single = false)
        {
            var path = AppDomain.CurrentDomain.BaseDirectory;
            var root = Path.GetPathRoot(path);

            string serverPath = root + PublicMethodApiController.FileloadStr + "\\" + "1\\" + FileType;//1代表OA系统
            if (id != 0)
            {
                if (!FileType.Equals((int)FileTypeEnum.ApkFile))
                {
                    serverPath += "\\" + id;
                }
            }
            if (Type != 0)
            {
                serverPath += "\\" + Type;
            }

            if (Single)
            {
                PublicTool.DeleteFile(serverPath, false);
            }
            if (!Directory.Exists(serverPath))
            {
                Directory.CreateDirectory(serverPath);
            }
            return serverPath;
        }
        #endregion

        public static string DownFileReplace(string filepath)
        {
            var path = AppDomain.CurrentDomain.BaseDirectory;
            var root = Path.GetPathRoot(path);
            var baspath = root + PublicMethodApiController.FileloadStr + "\\" + "1";
            filepath = filepath.Replace(baspath, PublicMethodApiController.FileloadMapping);
            return filepath;
        }

        #region 审批通用泛型方法
        /// <summary>
        /// 获取最后一位审批者的审批时间
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static DateTime? GetAuditTime<T>(T t) where T : PublicAudit
        {
            DateTime? dateTime = new DateTime();
            if (t.IsAuditEnd)
            {
                if (t.AuditTime6 != null)
                {
                    dateTime = t.AuditTime6;
                }
                else if (t.AuditTime5 != null)
                {
                    dateTime = t.AuditTime5;
                }
                else if (t.AuditTime4 != null)
                {
                    dateTime = t.AuditTime4;
                }
                else if (t.AuditTime3 != null)
                {
                    dateTime = t.AuditTime3;
                }
                else if (t.AuditTime2 != null)
                {
                    dateTime = t.AuditTime2;
                }
                else if (t.AuditTime1 != null)
                {
                    dateTime = t.AuditTime1;
                }
            }
            return dateTime;
        }
        #endregion

        // #region 获取当前用户所拥有的权限
        //  public static FormsAuthenticationTicket GetRight()
        //  {
        //      FormsAuthenticationTicket authTicket = null;
        //      //解密获取数据
        //      HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
        //      if (authCookie != null)
        //      {
        //          authTicket = FormsAuthentication.Decrypt(authCookie.Value);
        //          var rolestr = authTicket.Name;
        //      }
        //      return authTicket;
        //  }
        //  #endregion

        /// <summary>
        /// 消息表数据添加
        /// </summary>
        /// <param name="message">消息内容</param>
        /// <param name="receiver">接收人</param>
        /// <param name="type">消息类型</param>
        /// <returns></returns>
        private static bool AddMessage(string message, string receiver, string type, string url)
        {

            MessageTable table = new MessageTable();
            table.MainText = message;
            table.CreateTime = DateTime.Now;
            table.Receiver = Convert.ToInt32(receiver);
            table.MessageType = Convert.ToInt32(type);
            table.Url = url;
            db.MessageTable.Add(table);
            bool result = db.SaveChanges() > 0 ? true : false;
            return result;
        }
        #region 下载PDF文件格式


        public static string DownDPFByImg(string PDFFileName, string FilePath)
        {
            var filepath = string.Empty;
            using (PdfDocument document = new PdfDocument())
            {
                // 创建一个 PDF 文档
                PdfPage page = document.AddPage();
                XGraphics gfx = XGraphics.FromPdfPage(page);
                // 加载图片
                XImage image = XImage.FromFile(FilePath);
                // 计算缩放比例
                double targetWidth = 500; // 目标宽度
                double targetHeight = 800; // 目标高度
                double scale = Math.Min(targetWidth / image.PixelWidth, targetHeight / image.PixelHeight);
                double newWidth = image.PixelWidth * scale;
                double newHeight = image.PixelHeight * scale;
                gfx.DrawImage(image, 30, 30, newWidth, newHeight);
                // 设置图片放置的位置和大小
                //gfx.DrawImage(image, 100, 100);
                var dirpath = Path.GetDirectoryName(FilePath);
                // 保存 PDF 文件
                string filename = $"{PDFFileName}.pdf";
                filepath = Path.Combine(dirpath, filename);
                document.Save(filepath);
                // 释放资源
                image.Dispose();
                gfx.Dispose();
                document.Close();
            }
            return filepath;

        }


        /// <summary>
        /// 生成excel表格
        /// </summary>
        /// <param name="title"></param>
        /// <param name="data"></param>
        /// <param name="Pathfilename"></param>
        public static string createexcel(string[] title, List<string[]> data)
        {
            StringBuilder content = new StringBuilder();
            foreach (var item in data)
            {
                content.AppendLine(string.Join(',', item));
            }
            var result = $"{string.Join(',', title)}\r\n{content.ToString()}";
            return result;
        }


        #region 收方工资单/实发工资单
        /// <summary>
        /// 收方工资单Excel
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="form"></param>
        /// <param name="payroll"></param>
        /// <param name="ProjectName"></param>
        public DownFileProp CreateExcelToSFGZD(List<FormUser> form, PayrollForm payroll, string ProjectName)
        {
            {
                //var  Path=Document.CurrentDirectory;
                string currentDirectory = AppDomain.CurrentDomain.BaseDirectory;
                //获取模板文件地址
                var path = GetPaht((int)FileTypeEnum.Template, 0, 0);

                var newPath = GetPaht((int)FileTypeEnum.SFGZD, payroll.Id, 1);
                var FilesNames = Directory.GetFiles(path);
                var NewFileName = payroll.PayrollNumber + "收方工资单.xlsx";
                var TemplatefilePath = FilesNames.Where(x => x.Contains("收方工资单.xlsx")).LastOrDefault();
                //实发工资单
                if ((int)payroll.PayrollFormType == 2)
                {
                    newPath = GetPaht((int)FileTypeEnum.SFGZD, payroll.Id, 2);
                    FilesNames = Directory.GetFiles(path);
                    NewFileName = payroll.PayrollNumber + "实发工资单.xlsx";
                    TemplatefilePath = FilesNames.Where(x => x.Contains("实发工资单.xlsx")).LastOrDefault();
                }

                ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
                newPath = Path.Combine(newPath, NewFileName);
                File.Copy(TemplatefilePath, newPath, true);
                // 加载Excel文件
                FileInfo file = new FileInfo(newPath);
                using (ExcelPackage package = new ExcelPackage(file))
                {
                    
                    // 获取第一个工作表
                    ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
                    // 修改单元格中的数据
                    //((object[,])worksheet.Cells.Value)[1, 1]="1231312";
                    //工程名称
                    worksheet.Cells["C2"].Value = ProjectName;
                    //施工类别
                    worksheet.Cells["C3"].Value = payroll.ConstructionType.GetDescription();
                    //编号
                    worksheet.Cells["I2"].Value = payroll.PayrollNumber;
                    //日期
                    worksheet.Cells["I3"].Value = DateTime.Today.ToString("yyyy/MM/dd");
                    //施工部位
                    worksheet.Cells["A5"].Value = payroll.ConstructionPart;
                    //工作内容
                    worksheet.Cells["D5"].Value = payroll.JobContent;
                    //方量  
                    worksheet.Cells["E5"].Value = payroll.Squarequantity;
                    //单价  
                    worksheet.Cells["F5"].Value = payroll.Price;
                    //总金额 
                    worksheet.Cells["G5"].Value = payroll.Totalprice;
                    //责任人 
                    worksheet.Cells["H5"].Value = db.Users.FirstOrDefault(x => x.Id == payroll.PersonId).UserName;
                    //签名 
                    worksheet.Cells["I5"].Value = "";
                    //备注
                    worksheet.Cells["J5"].Value = payroll.Remarks;

                    SetExcelTxt(worksheet, form);
                    // 保存修改后的Excel文件
                    package.Save();
                }

                if ((int)payroll.PayrollFormType == 2)
                {
                    return new DownFileProp() { id = payroll.Id, Type = 2, FileType = (int)FileTypeEnum.SFGZD, FileName = NewFileName };
                }
                return new DownFileProp() { id = payroll.Id, Type = 1, FileType = (int)FileTypeEnum.SFGZD, FileName = NewFileName };
            }

        }

        /// <summary>
        /// 写入人员对象实体
        /// </summary>
        /// <param name="worksheet"></param>
        /// <param name="form"></param>
        private void SetExcelTxt(ExcelWorksheet worksheet, List<FormUser> form)
        {
            var dataUser = db.Users.Where(x => !x.Delete).ToList();
            int rowIndex = 7;
            decimal day = 0;
            decimal money = 0;
            foreach (var item in form)
            {
                worksheet.InsertRow(rowIndex, 1);
                // 设置行高为40px
                worksheet.Row(rowIndex).Height = 30;
                worksheet.Cells[$"G{rowIndex}:H{rowIndex}"].Merge = true;
                var user = dataUser.FirstOrDefault(x => x.Id.Equals(item.UserId));
                // 添加框线并设置内容
                for (char column = 'A'; column <= 'J'; column++)
                {

                    var cell = worksheet.Cells[column.ToString() + rowIndex];
                    cell.Style.Border.Top.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                    cell.Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                    cell.Style.Border.Left.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                    cell.Style.Border.Right.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                    cell.Style.Font.Bold = true; // 加粗
                    cell.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center; // 水平居中
                    cell.Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center; // 垂直居中
                    if (column == 'A')
                    {
                        var index = worksheet.Cells[column.ToString() + (rowIndex - 1)].Value;
                        if (rowIndex == 7)
                        {
                            index = 0;
                        }
                        worksheet.Cells[column.ToString() + (rowIndex)].Value = (Convert.ToInt32(index) + 1).ToString();
                    }
                    else if (column != 'H')
                    {

                        cell.Style.Border.Top.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                        cell.Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                        cell.Style.Border.Left.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                        cell.Style.Border.Right.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                        if (column == 'B')
                        {
                            cell.Value = user.UserName;
                        }
                        if (column == 'C')
                        {
                            cell.Value = user.UserNumber;
                        }
                        if (column == 'D')
                        {
                            cell.Value = item.JobContent;
                        }
                        if (column == 'E')
                        {
                            cell.Value = item.WorkingDays;
                            day = day + item.WorkingDays;
                        }
                        if (column == 'F')
                        {
                            cell.Value = item.Price.ToString("0.00");
                        }
                        if (column == 'G')
                        {
                            decimal Money = item.WorkingDays * Convert.ToDecimal(item.Price.ToString("0.00"));
                            cell.Value = Money;
                            money = money + Money;
                        }
                        if (column == 'J')
                        {
                            cell.Value = item.Remarks;
                        }
                    }

                }
                rowIndex++;
            }
            worksheet.Cells["E".ToString() + (rowIndex)].Value = day;

            worksheet.Cells["E".ToString() + (rowIndex)].Style.Font.Bold = true; // 加粗
            worksheet.Cells["E".ToString() + (rowIndex)].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center; // 水平居中
            worksheet.Cells["E".ToString() + (rowIndex)].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center; // 垂直居中
            worksheet.Cells["G".ToString() + (rowIndex)].Value = money;
            worksheet.Cells["G".ToString() + (rowIndex)].Style.Font.Bold = true; // 加粗
            worksheet.Cells["G".ToString() + (rowIndex)].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center; // 水平居中
            worksheet.Cells["G".ToString() + (rowIndex)].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center; // 垂直居中
        }
        #endregion


        #region 报销工资单
        /// <summary>
        /// 收方工资单Excel
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="form"></param>
        /// <param name="payroll"></param>
        /// <param name="ProjectName"></param>
        /// 
        public DownFileProp CreateExcelToBXD(List<ReimRule> form, FinanceReimbursementReim payroll, string ProjectName)
        {
            try
            {
                {
                    //var  Path=Document.CurrentDirectory;
                    string currentDirectory = AppDomain.CurrentDomain.BaseDirectory;
                    //获取模板文件地址
                    var path = GetPaht((int)FileTypeEnum.Template, 0, 0);

                    var newPath = GetPaht((int)FileTypeEnum.FinanceResFile, payroll.Id, 3);
                    var FilesNames = Directory.GetFiles(path);
                    var NewFileName = payroll.ReimNumber + "报销单.xlsx";
                    var TemplatefilePath = FilesNames.Where(x => x.Contains("报销单.xlsx")).LastOrDefault();
                    ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
                    newPath = Path.Combine(newPath, NewFileName);
                    File.Copy(TemplatefilePath, newPath, true);
                    // 加载Excel文件
                    FileInfo file = new FileInfo(newPath);
                    using (ExcelPackage package = new ExcelPackage(file))
                    {
                        // 获取第一个工作表
                        ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
                        //工程名称
                        worksheet.Cells["C2"].Value = ProjectName;
                        //编号
                        worksheet.Cells["E2"].Value = payroll.ReimNumber;
                        //报销类型
                        worksheet.Cells["C3"].Value = command.GetEnumDescription(payroll.FinanceReimbursementReimType);
                        //日期
                        worksheet.Cells["E3"].Value = DateTime.Today.ToString("yyyy/MM/dd");
                        SetBXDExcelTxt(worksheet, form);
                        // 保存修改后的Excel文件
                        package.Save();
                    }
                    return new DownFileProp() { id = payroll.Id, Type = 3, FileType = (int)FileTypeEnum.FinanceResFile, FileName = NewFileName };
                }
            }
            catch (Exception ex)
            {
                throw ;
            }
        }

        /// <summary>
        /// 人员报销
        /// </summary>
        /// <param name="worksheet"></param>
        /// <param name="form"></param>
        private void SetBXDExcelTxt(ExcelWorksheet worksheet, List<ReimRule> form)
        {

            int rowIndex = 5;
            decimal money = 0;
            var index = 0;
            foreach (var item in form)
            {
                worksheet.InsertRow(rowIndex, 1);
                // 设置行高为40px
                worksheet.Row(rowIndex).Height = 50;
                index++;
                // 添加框线并设置内容
                for (char column = 'A'; column <= 'F'; column++)
                {
                    var cell = worksheet.Cells[column.ToString() + rowIndex];
                    cell.Style.Border.Top.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                    cell.Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                    cell.Style.Border.Left.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                    cell.Style.Border.Right.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                    cell.Style.Font.Bold = true; // 加粗
                    cell.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center; // 水平居中
                    cell.Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center; // 垂直居中
                    if (column == 'A')
                    {
                        worksheet.Cells[column.ToString() + (rowIndex)].Value = (Convert.ToInt32(index)).ToString();
                    }
                    {

                        if (column == 'B')
                        {
                            cell.Value = item.ReimRuleContent;
                        }
                        if (column == 'C')
                        {
                            cell.Value = item.Abstract;
                        }
                        if (column == 'D')
                        {
                            cell.Value = item.ReimRuleCertificate;
                        }
                        if (column == 'E')
                        {
                            decimal Money = Convert.ToDecimal(item.ReimRuleMoney.ToString("0.00"));
                            cell.Value = Money;
                            money = money + Money;
                        }
                        if (column == 'F')
                        {
                            cell.Value = item.Remark;
                        }
                    }
                }
                rowIndex++;
            }
            worksheet.Cells["E".ToString() + (rowIndex)].Value = money;
            worksheet.Cells["E".ToString() + (rowIndex)].Style.Font.Bold = true; // 加粗
            worksheet.Cells["E".ToString() + (rowIndex)].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center; // 水平居中
            worksheet.Cells["E".ToString() + (rowIndex)].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center; // 垂直居中
            var Result = Tool.command.ConvertToChineseCapital(money);
            worksheet.Cells["C".ToString() + (rowIndex + 1)].Value = Result;
            worksheet.Cells["C".ToString() + (rowIndex + 1)].Style.Font.Bold = true; // 加粗
            worksheet.Cells["C".ToString() + (rowIndex + 1)].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center; // 水平居中
            worksheet.Cells["C".ToString() + (rowIndex + 1)].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center; // 垂直居中
        }
        #endregion


        #region 生活费 工资发放表

        /// <summary>
        /// 生活费单Excel
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="form"></param>
        /// <param name="payroll"></param>
        /// <param name="ProjectName"></param>
        /// 
        public DownFileProp CreateExcelToLiving(List<ExportRequestProp> props)
        {
            try
            {
                {
                    //var  Path=Document.CurrentDirectory;
                    string currentDirectory = AppDomain.CurrentDomain.BaseDirectory;
                    //获取模板文件地址
                    var path = GetPaht((int)FileTypeEnum.Template, 0, 0);

                    var LivingeBatch = props.FirstOrDefault().LivingeId;
                    var  newPath = GetPaht((int)FileTypeEnum.SFGZD, LivingeBatch, 3);
                    var FilesNames = Directory.GetFiles(path);
                    //多次导出.保留以记录
                    var NewFileName = "工资发放表"+DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
                    var TemplatefilePath = FilesNames.Where(x => x.Contains("工资发放表")).LastOrDefault();
                    ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
                    newPath = Path.Combine(newPath, NewFileName);
                    File.Copy(TemplatefilePath, newPath, true);
                    // 加载Excel文件
                    FileInfo file = new FileInfo(newPath);
                    using (ExcelPackage package = new ExcelPackage(file))
                    {
                        // 获取第一个工作表
                       int worksheetcount = package.Workbook.Worksheets.Count;
                        ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
                        // 总金额
                        worksheet.Cells["B1"].Value = props.Sum(x=>x.Money);
                        //总笔数
                        worksheet.Cells["B2"].Value = props.Count();

                        SetBXDExcelLiving(worksheet, props);
                        // 保存修改后的Excel文件
                        package.Save();
                    }
                    return new DownFileProp() { id = LivingeBatch, Type = 3, FileType = (int)FileTypeEnum.SFGZD, FileName = NewFileName };
                }
            }
            catch (Exception ex)
            {
               
                throw;
            }
        }

        /// <summary>
        /// 生活费发放
        /// </summary>
        /// <param name="worksheet"></param>
        /// <param name="form"></param>
        private void SetBXDExcelLiving(ExcelWorksheet worksheet, List<ExportRequestProp> form)
        {

            int rowIndex = 4;
            var index = 0;
            foreach (var item in form)
            {
                worksheet.InsertRow(rowIndex, 1);
                // 设置行高为40px
                worksheet.Row(rowIndex).Height = 20;
                index++;
                // 添加框线并设置内容
                for (char column = 'A'; column <= 'E'; column++)
                {
                    var cell = worksheet.Cells[column.ToString() + rowIndex];
                    //cell.Style.Border.Top.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                    //cell.Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                    //cell.Style.Border.Left.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                    //cell.Style.Border.Right.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                    //cell.Style.Font.Bold = true; // 加粗
                    cell.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center; // 水平居中
                    cell.Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center; // 垂直居中
                    if (column == 'A')
                    {
                        cell.Value = item.BankCardNumber;
                    }
                    {

                        if (column == 'B')
                        {
                            cell.Value = item.UserName;
                        }
                        if (column == 'C')
                        {
                            cell.Value = item.Money;
                        }
                        if (column == 'D')
                        {
                            cell.Value = item.LivingeBatch+"-工资";
                        }
                        if (column == 'E')
                        {
                            cell.Value = item.LivingeBatch;
                        }
                      
                    }
                }
                rowIndex++;
            }
            
        }



        #endregion



        #region 年工资表导出


      
           /// <summary>
          /// 收方工资单Excel
          /// </summary>
          /// <param name="filePath"></param>
          /// <param name="form"></param>
          /// <param name="payroll"></param>
          /// <param name="ProjectName"></param>
          /// 
          public DownFileProp CreateExcelToNGZ(List<NDGZDDto> data,string year)
          {
              try
              {
                  {
                      //var  Path=Document.CurrentDirectory;
                      string currentDirectory = AppDomain.CurrentDomain.BaseDirectory;
                    //获取模板文件地址
                    var fileName = DateTime.Now.ToString("yyyyMMdd") + $"{year}年度工资.xlsx";
                      var newPath = Path.Combine(GetPaht((int)FileTypeEnum.NGZD, 1, 1), fileName);
                    ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
                    using (ExcelPackage package = new ExcelPackage())
                      {
                        // 获取第一个工作表
                        ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet1");
                        SetExcelNZHSMode(worksheet, data, year);
                        FileInfo existingFile = new FileInfo(newPath);
                        // 保存修改后的Excel文件
                        package.SaveAs(existingFile);
                      }
                      return new DownFileProp() { id = 1, Type = 1, FileType = (int)FileTypeEnum.NGZD, FileName = fileName };
                  }
              }
              catch (Exception ex)
              {
                return null;
              }
          }
        #endregion

        private void SetExcelNZHSMode(ExcelWorksheet worksheet, List<NDGZDDto> data,string year)
        {
            int index = 1;
            foreach (var item in data)
            {
                if (item.FormuserInfo.Count==0)
                {
                    continue;
                }
                //合并单元格
                var title = worksheet.Cells[$"A{index}:G{index}"];
                title = cellstyle(title);
                title.Value = $"{year}年--{item.UserName}";
                title.Merge = true;
                index++;
                worksheet.Cells[$"A{index}"].Value="序号";
                worksheet.Cells[$"B{index}"].Value= "项目";
                worksheet.Cells[$"C{index}"].Value= "总金额";
                worksheet.Cells[$"D{index}"].Value= "报销合计";
                worksheet.Cells[$"E{index}"].Value= "生活费合计";
                worksheet.Cells[$"F{index}"].Value= "社保";
                worksheet.Cells[$"G{index}"].Value= "工资余额";
                index++;
                SetexcelNDGZdata(worksheet, item, index);
                index = index + 3;
            }
        }

        private void  SetexcelNDGZdata(ExcelWorksheet worksheet,  NDGZDDto data,int index)
        {
           int indexNumber=0;
            int startIndex = index;
            decimal SumTotalPrice = 0;
            decimal ReimRuleTotalPrice = 0;
            foreach (var item in data.FormuserInfo.GroupBy(x=>x.ProjectId))
            {

                indexNumber++;
                decimal SumTotalPricevalue = Convert.ToDecimal( item.Sum(x => x.TotalPrice)); 
                decimal ReimRuleTotalPricevalue = Convert.ToDecimal(data.ReimRuleInfo.Where(x => x.ProjectId == item.Key).Sum(x => x.ReimRuleMoney)); 
                worksheet.Cells[$"A{index}"].Value = indexNumber;
                worksheet.Cells[$"B{index}"].Value =db.Project.FirstOrDefault(x=>x.Id == item.Key).ProjectName;
                worksheet.Cells[$"C{index}"].Value = SumTotalPricevalue;
                worksheet.Cells[$"D{index}"].Value = ReimRuleTotalPricevalue;
                SumTotalPrice += SumTotalPricevalue;
                ReimRuleTotalPrice += ReimRuleTotalPricevalue;
                if (data.FormuserInfo.GroupBy(x => x.ProjectId).Count() == indexNumber)
                {
                    worksheet.Cells[$"E{startIndex}:E{index}"].Value = data.LivingExpensesTotal;
                    worksheet.Cells[$"E{startIndex}:E{index}"].Merge = true;
                    worksheet.Cells[$"F{startIndex}:F{index}"].Value = data.Socialinsurance;
                    worksheet.Cells[$"F{startIndex}:F{index}"].Merge = true;
                    worksheet.Cells[$"G{startIndex}:G{index}"].Value = SumTotalPrice - ReimRuleTotalPrice - Convert.ToDecimal(data.LivingExpensesTotal);
                    worksheet.Cells[$"G{startIndex}:G{index}"].Merge = true;

                }
                index++;
            } 
        }
        private   ExcelRange cellstyle(ExcelRange cell)
        {
             cell.Style.Border.Top.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
             cell.Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
             cell.Style.Border.Left.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
             cell.Style.Border.Right.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
             cell.Style.Font.Bold = true; // 加粗
             cell.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center; // 水平居中
             cell.Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center; // 垂直居中
            return cell;
        }
        #endregion



    }
}
